179. Largest Number - jiejackyzhang/leetcode-note GitHub Wiki

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.

解题思路为string的比较。

比如"9"和"94",将它们连接后,994 > 949,因此9应该在94前面。

  1. 首先将nums转换为string[]数组;
  2. 采用string的排序算法对数组排序;
  3. 将数组转换为string。
public class Solution {
    public String largestNumber(int[] nums) {
        if(nums == null || nums.length == 0) return "0";
        String[] strs = new String[nums.length];
        for(int i = 0; i < nums.length; i++) strs[i] = String.valueOf(nums[i]);
        // sort strs in descending order
        Arrays.sort(strs, new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                String s1 = a + b;
                String s2 = b + a;
                return s2.compareTo(s1);
            }
        });
        if(strs[0].equals("0")) return "0"; // if all in strs are "0"s
        StringBuilder sb = new StringBuilder();
        for(String s : strs) {
            sb.append(s);
        }
        return sb.toString();
    }
}
⚠️ **GitHub.com Fallback** ⚠️