How can I manipulate an array to make the largest number?

前端 未结 16 2349
暖寄归人
暖寄归人 2021-01-30 02:47

Say you have an array of positive integers, manipulate them so that the concatenation of the integers of the resultant array is the largest number possible. Ex: {9,1,95,17,5}, r

16条回答
  •  我在风中等你
    2021-01-30 03:16

    The idea of @Nate Kohl is very good. I just implemented a Java version using quicksort. Here it is:

    import java.util.Random;
    
    public class Sort_MaxConcatenation {
        private Random r = new Random();
    
        public void quicksort_maxConcatenation(int[] a, int begin, int end) {
            if (begin < end) {
                int q = partition(a, begin, end);
                quicksort_maxConcatenation(a, begin, q);
                quicksort_maxConcatenation(a, q + 1, end);
            }
        }
    
        private int partition(int[] a, int begin, int end) {
            int p = begin + r.nextInt(end - begin + 1);
            int t1 = a[p];
            a[p] = a[end];
            a[end] = t1;
    
            int pivot = t1;
            int q = begin;
            for (int i = begin; i < end; i++) {
                if (compare_maxConcatenation(a[i], pivot) > 0) {
                    int t2 = a[q];
                    a[q] = a[i];
                    a[i] = t2;
                    q++;
                }
            }
            int t3 = a[q];
            a[q] = a[end];
            a[end] = t3;
    
            return q;
        }
    
        private int compare_maxConcatenation(int i, int j) {
            int ij = Integer.valueOf(String.valueOf(i).concat(String.valueOf(j)));
            int ji = Integer.valueOf(String.valueOf(j).concat(String.valueOf(i)));
            if (ij > ji)
                return 1;
            else if (ij == ji)
                return 0;
            return -1;
        }
    
        public static void main(String[] args) {
    
            int[] a = new int[]{56, 5, 4, 94, 9, 14, 1};
            Sort_MaxConcatenation smc = new Sort_MaxConcatenation();
            smc.quicksort_maxConcatenation(a, 0, a.length-1);
            for(int i = 0;i < a.length;i++) {
                System.out.print(a[i]);
            }
        }
    }
    

提交回复
热议问题