Skip to content

Latest commit

 

History

History
36 lines (30 loc) · 1.12 KB

179. Largest Number.MD

File metadata and controls

36 lines (30 loc) · 1.12 KB

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.

   public String largestNumber(int[] nums) {
    	String[] strs = new String[nums.length];
    	for(int i = 0; i < nums.length; i++){
    		strs[i] = String.valueOf(nums[i]);
    	}
    	Arrays.sort(strs,  new Comparator<String>(){

			public int compare(String arg0, String arg1) {
				String i = arg0 + arg1;
				String j = arg1 + arg0;
				return j.compareTo(i);
			} 		
    	});
    	StringBuffer sb = new StringBuffer();
    	for(int i = 0; i < strs.length; i++){
    		sb.append(strs[i]);
    	}
    	String res = sb.toString();
    	if(res.charAt(0) == '0'){
    	    return "0";
    	}
    	return res;         
    }

**思路:**这题的解法是从高位比,利用了java的Arrays的sort()方法.虽然通过了,但是效率不高,有空再想一下快速排序法。