179. Largest Number

Given a list of non negative integers, arrange them such that they form the largest number.

Example 1:

Input: [10,2]
Output: "210"

Example 2:

Input: [3,30,34,5,9]
Output: "9534330"

Note: The result may be very large, so you need to return a string instead of an integer.

class Solution {
    private class LargerNumberComparator implements Comparator<String> {
        @Override
        public int compare(String a, String b) {
            String order1 = a + b;
            String order2 = b + a;
           return order2.compareTo(order1);
        }
    }

    public String largestNumber(int[] nums) {
        // Get input integers as strings.
        String[] asStrs = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            asStrs[i] = String.valueOf(nums[i]);
        }

        // Sort strings according to custom comparator.
        Arrays.sort(asStrs, new LargerNumberComparator());

        // If, after being sorted, the largest number is `0`, the entire number
        // is zero.
        if (asStrs[0].equals("0")) {
            return "0";
        }

        // Build largest number from sorted array.
        String largestNumberStr = new String();
        for (String numAsStr : asStrs) {
            largestNumberStr += numAsStr;
        }

        return largestNumberStr;
    }
}

重写comparator interface 里面的compare方法,然后使用method Arrays.sort(array[], new Comparator<String>());

a+b比b+a是升序,b+a比a+b是降序排列。

While it might be tempting to simply sort the numbers in descending order, this causes problems for sets of numbers with the same leading digit.

For example, sorting the problem example in descending order would produce the number 95343039534303,

while the correct answer can be achieved by transposing the 33 and the 3030. Therefore, for each pairwise comparison during the sort,

we compare the numbers achieved by concatenating the pair in both orders. We can prove that this sorts into the proper order as follows:

就是说"3" "30"的时候,会判断出30比3大,所以30在前面生成303,我们想要的其实是330.

所以用3+30和30+3比较,结果自然是330比较大。

再说一下compareTo方法,比如3和1,比较结果就是2,4和1,结果是3,相反就加负号。

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10687369.html