跳转至

179. Largest Number

Leetcode Sort

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.

分析

最大数问题。把数字转化为字符串,然后比较字符串,把字符串连接起来得到结果。怎么比较字符串呢?比较字符串放在前面和后面形成的两种字符串。还需要注意全是0的情况。

利用函数式编程写的和普通方式写的。

public String largestNumber(int[] nums) {
    if(nums == null || nums.length == 0) return null;
    String[] str = new String[nums.length];
    for(int i = 0; i < nums.length; i ++)
        str[i] = Integer.toString(nums[i]); 
    Arrays.sort(str, new Comparator<String>() {
        public int compare(String a, String b) {
            return -(a+b).compareTo(b+a);
        }
    });

    // If, after being sorted, the largest number is `0`, 
    // the entire number is zero.
    if (str[0].equals("0") && str.length > 1) return "0";

    StringBuilder res = new StringBuilder();
    for(String s : str) res.append(s);
    return res.toString();
}
public String largestNumber(int[] nums) {
    // to string array
    String[] a = Arrays.stream(nums).
        mapToObj(Integer::toString).
        toArray(String[]::new);
    // sort and concat
    String res = Arrays.stream(a).
        sorted(((o1, o2) ->o2.concat(o1).compareTo(o1.concat(o2)))).
        collect(Collectors.joining());
    // special occasion: all zero
    if (res.charAt(0) == '0' && res.length() > 1)
        return "0";
    return res;
}

时间复杂度是O(n\log n),空间复杂度是O(n).