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.
对于arraylist 用Collection.sort(arraylist, comparator) array用 Arrays.sort(array, comparator)
a.compareTo(b) 如果a大 return +, 小return - , eq return=
public class Solution { public String largestNumber(int[] nums) { if (nums == null || nums.length == 0) { return ""; } String[] str = new String[nums.length]; for (int i = 0; i < nums.length; i++) { str[i] = String.valueOf(nums[i]); } Arrays.sort(str, new Comparator() { public int compare(String s1, String s2) { String l1 = s1 + s2; String l2 = s2 + s1; return l2.compareTo(l1);//为了使数值大的排在前面 } }); StringBuilder sb = new StringBuilder(); for (String s : str) { sb.append(s); } if (sb.charAt(0) == '0') { return "0"; } return sb.toString(); } }
没有评论:
发表评论