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

179 Largest Number

时间:2017-10-09 09:56:26      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:大小   char   public   去掉   compare   ges   integer   compareto   rri   

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.

聪明方法:其实干嘛要挨个比呢,按最直接的方法,接起来,谁大谁在前:

可以换一下思路,要想比较两个数在最终结果中的先后位置,何不直接比较一下不同组合的结果大小?

举个例子:要比较3和34的先后位置,可以比较334和343的大小,而343比334大,所以34应当在前。

这样,有了比较两个数的方法,就可以对整个数组进行排序。然后再把排好序的数拼接在一起就好了。

首先把int 全部转换成string array,然后,自己写一个comparator,判断ab ba的大小,从而把a,b排序

然后把所有的连起来,记住,大的在后面,从后面开始连接。最后去掉前面的0;

 

public class Solution {
     public String largestNumber(int[] num) {
        if(num == null || num.length == 0)
            return "";
        
        // Convert int array to String array, so we can sort later on
        String[] s_num = new String[num.length];
        for(int i = 0; i < num.length; i++)
            s_num[i] = String.valueOf(num[i]);
            
        // Comparator to decide which string should come first in concatenation
        Comparator<String> comp = new Comparator<String>(){
            @Override
            public int compare(String str1, String str2){
                String s1 = str1 + str2;
            String s2 = str2 + str1;
            return s2.compareTo(s1); // reverse order here, so we can do append() later
            }
        };
        
        Arrays.sort(s_num, comp);
                // An extreme edge case by lc, say you have only a bunch of 0 in your int array
                if(s_num[0].charAt(0) == ‘0‘)
                    return "0";
            
        StringBuilder sb = new StringBuilder();
        for(String s: s_num)
                sb.append(s);
        
        return sb.toString();
        
    }
}
奇技淫巧:

Comparator<String> comp = new Comparator<String>(){ @Override public int compare(String str1, String str2){ String s1 = str1 + str2; String s2 = str2 + str1; return s2.compareTo(s1); // reverse order here, so we can do append() later } };

179 Largest Number

标签:大小   char   public   去掉   compare   ges   integer   compareto   rri   

原文地址:http://www.cnblogs.com/apanda009/p/7639483.html

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