LeetCode 179. Largest Number (最大数)

题目标签:Sort

题目给了一组 数字,让我们组成一个最大数返回。

从example 2 看出,排序不是按照一般的大小,而是按照搭配组合,比较大小后才得出结果。

3, 30 的结果是 330 大于 303, 所以 3 要排序在 30 之前。

建立一个cutom comparator来实现,具体看code。

Java Solution: 

Runtime:  5ms, faster than 76.83% 

Memory Usage: 39.7MB, less than 21.46%

完成日期:6/21/2020

关键点:custom comparator

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 00..., return 0
        if(asStrs[0].equals("0")) {
            return "0";
        }
        
        // build largest number from sorted array.
        String largestNumberStr = new String();
        for( String str : asStrs) {
            largestNumberStr += str;
        }
        
        return largestNumberStr;   
    }
}

参考资料:https://leetcode.com/problems/largest-number/solution/

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/