8.15 [LeetCode] 179 Largest Number

[LeetCode 179] Largest Number

COMMENTS

Question

link

 

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.

 

Show Tags
Sort

Analysis

Please refer to [[ItInt5] Numbers Concatenation Max (Largest Number)(/blog/2014/08/17/Numbers-Concatenation-Max/).

Solution

Note that we can not override Comparator(Integer). So we must first convert int to string then sort.

Code

public class Solution {
    public String largestNumber(int[] nums) {
        if(nums == null || nums.length == 0)
            return "0";
        String[] str = new String[nums.length];
        for(int i = 0; i < nums.length; i++)
            str[i] = Integer.toString(nums[i]);
        Arrays.sort(str, new desecComp());
        StringBuilder sb = new StringBuilder();
        for(String s : str){
            
            if(sb.toString().length() == 0 && s.equals("0")) // use str.equals(str2) instead of str == str2 will be more stable;
                continue; // omit 0s in the beginning.
            else
                sb.append(s);
        }
        if(sb.toString().equals("")) 
            return "0";
        return sb.toString();
    }

    class desecComp implements Comparator<String> { // do not forget "<String>" and this class is in the whole class
        public int compare(String s1, String s2) { // the return type is int!!! and the function name is compare not class name
            String a = s1 + s2;
            String b = s2 + s1;
            return b.compareTo(a); // descending order so we use b To a
        }    
    } 
}

 

posted @ 2015-08-16 12:18  YoungAndSimple  阅读(153)  评论(0编辑  收藏  举报