Largest Number

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

For example, given [3, 30, 34, 5, 9], the largest formed number is
9534330.

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

排序法

复杂度

O(nklgnk) 时间 O(N) 空间

思路

这题没法用integer做,得弄成string做,排序
唯一的难点是排序的时候comparator,这么写:

class MyComp implements Comparator<String> {
    public int compare(String a, String b) {
        String s1 = a + b;
        String s2 = b + a;
        return s2.compareTo(s1);
    }
}

多么的天才!
Credit to: https://discuss.leetcode.com/category/187/largest-number

注意

都是0的情况要注意,特殊判断一下

代码

public class Solution {
    class MyComp implements Comparator<String> {
        public int compare(String a, String b) {
            String s1 = a + b;
            String s2 = b + a;
            return s2.compareTo(s1);
        }
    }
    public String largestNumber(int[] nums) {
        String[] arr = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            arr[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(arr, new MyComp());
        if (arr[0].equals("0"))
            return "0";
        StringBuilder sb = new StringBuilder();
        for (String s : arr) {
            sb.append(s);
        }
        return sb.toString();
    }
}

liuqi627
364 声望100 粉丝