#leetcode#179. Largest Number

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ChiBaoNeLiuLiuNi/article/details/72638915

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.

--------------------------------------------------------------------------------------------------------------------------------------------------

考点就是comparator的用法,这里注意用(s1+s2).compareTo(s2+s1) 来排序{12, 121}的结果是{121, 12}
排序完之后组成String要从面开始append,当然如果用(s2+s1).compareTo(s1+s2)排序的顺序会反过来

还有就是注意都是0这个conor case,比如一串0,0,0,0,0, 应该返回“0”, 而不是“00000”

public class Solution {
    public String largestNumber(int[] nums) {
        if(nums == null || nums.length == 0)
            return "";
        String[] strs = new String[nums.length];
        for(int i = 0; i < nums.length; i++){
            strs[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(strs, new Comparator<String>(){
            @Override
            public int compare(String s1, String s2){
                return (s1 + s2).compareTo(s2 + s1);//从小到大
            }
        });
        StringBuilder sb = new StringBuilder();
        for(int i = strs.length - 1; i >= 0; i--){
            sb.append(strs[i]);
        }
        
        return sb.charAt(0) == '0' ? "0" : sb.toString();
    }
}


猜你喜欢

转载自blog.csdn.net/ChiBaoNeLiuLiuNi/article/details/72638915
今日推荐