码迷,mamicode.com
首页 > 其他好文 > 详细

8.15 [LeetCode] 179 Largest Number

时间:2015-08-16 13:43:54      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

[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
        }    
    } 
}

 

8.15 [LeetCode] 179 Largest Number

标签:

原文地址:http://www.cnblogs.com/michael-du/p/4734009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!