1. 程式人生 > >#leetcode#179. Largest Number

#leetcode#179. 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.

--------------------------------------------------------------------------------------------------------------------------------------------------
考點就是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();
    }
}