LeetCode-Largest Number

LiBlog發表於2016-09-12

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Analysis:

We sort the numbers in a sequence that for any number i and j, if (String) i+j > (String) j+i, then we choose i before j.

Solution:

public class Solution {
    public String largestNumber(int[] nums) {
        if (nums.length==0) return "";
        List<char[]> numStrs = new ArrayList<char[]>();
        for (int i=0;i<nums.length;i++){
            numStrs.add(Integer.toString(nums[i]).toCharArray());
        }
        
        Collections.sort(numStrs,new Comparator<char[]>(){
            public int compare(char[] n1, char[] n2){
                char[] d1 = new char[n1.length+n2.length];
                char[] d2 = new char[n1.length+n2.length];
                for (int i=0;i<n1.length;i++){
                    d1[i] = n1[i];
                    d2[n2.length+i] = n1[i];
                }
                for (int i=0;i<n2.length;i++){
                    d1[i+n1.length] = n2[i];
                    d2[i] = n2[i];
                }
                
                for (int i=0;i<d1.length;i++)
                    if (d1[i]!=d2[i]){
                        return (int)d1[i]-(int)d2[i];
                    }
                
                return 0;
            }
        });
        
        StringBuilder builder = new StringBuilder();
        builder.append(numStrs.get(numStrs.size()-1));
        if (builder.toString().equals("0")) return "0";
        
        for (int i=numStrs.size()-2;i>=0;i--){
            builder.append(numStrs.get(i));
        }
        return builder.toString();
        
    }
}

 

相關文章