179. Largest Number 用数组中的元素凑一个最大数字

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

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

 

Example 1:

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

Example 2:

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

Example 3:

Input: nums = [1]
Output: "1"

Example 4:

Input: nums = [10]
Output: "10"

思路:首先排序,但也30 > 9 这样的也不对啊
正解:利用了s2.compareTo(s1)这个自带的函数,按lexi排序

 

Comparator接口,用法上和抽象类一样吧。就按类来写就行了

 

class Solution {
    public String largestNumber(int[] nums) {
        //cc
        if (nums == null || nums.length == 0)
            return "";        
        
        //转成string[]
        String[] strs = new String[nums.length];
        for (int i = 0; i < strs.length; i++) {
            strs[i] = String.valueOf(nums[i]);
        }
        
        //写个排序
        Comparator<String> comparator = new Comparator<String>(){            
            @Override
            public int compare(String s1, String s2) {
                String str1 = s1 + s2;
                String str2 = s2 + s1;                
                return str2.compareTo(str1);
            }
        };
        
        //排序
        Arrays.sort(strs, comparator);
        
        // An extreme edge case by lc, say you have only a bunch of 0 in your int array
        if(strs[0].charAt(0) == '0')
            return "0";
        
        //粘贴一下
        StringBuilder sb = new StringBuilder();
        for (String str : strs) {
            sb.append(str);
        }
        
        return sb.toString();
    }
}
View Code

 

 

 

 
posted @ 2020-10-20 10:46  苗妙苗  阅读(129)  评论(0)    收藏  举报