[LeetCode] 179. Largest Number Java

题目:

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.

题意及分析:给出一个数组,求用数组里的元素能组成的最大数。我们可以随便去两个元素来看:s1=782,s2=9,那么s1+s2=7829,s2+s1=9782,我们可以得到s2在s1前面得到的数一定比s1在s2前面打,所以,我们可以用s1+s2与s2+s1的大小判断哪个元素在前面。最后用一个stringbuilder,这样就不用重复创建新string对象了

代码:

public class Solution {
    public String largestNumber(int[] nums) {
        if(nums == null || nums.length == 0)
		    return "";
        String[] strings = new String[nums.length];
        
        for(int i=0;i<nums.length;i++){
        	strings[i]=nums[i]+"";
        }
        
        Arrays.sort(strings,new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				// TODO Auto-generated method stub
				String s1=o1+o2;
				String s2=o2+o1;
				return s2.compareTo(s1);
			}
        	
		});
        if (strings[0].charAt(0) == '0') return "0";  //最前面的数为0,说明数组全部为0,这时候返回0
        StringBuilder reStringBuilder=new StringBuilder();
        for(int i=0;i<strings.length;i++){
        	reStringBuilder.append(strings[i]);
        }
        //System.out.println(reStringBuilder.toString());
        return reStringBuilder.toString();
    }
}

 

  

 

posted @ 2017-07-01 10:54  荒野第一快递员  阅读(793)  评论(0编辑  收藏  举报