class Solution { private class LargerNumberComparator implements Comparator<String> { @Override public int compare(String a, String b) { String order1 = a + b; String order2 = b + a; return order2.compareTo(order1); } }
public String largestNumber(int[] nums) { String[] tmpNums = new String[nums.length]; for(int i=0;i<nums.length;i++) tmpNums[i] =String.valueOf(nums[i]); Arrays.sort(tmpNums, new LargerNumberComparator()); if(tmpNums[0].equals("0")) return "0"; StringBuilder sb = new StringBuilder(); for(String s:tmpNums){ sb.append(s); } return sb.toString(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//golang func largestNumber(nums []int) string { ss := make([]string, len(nums)) for i, num := range nums { ss[i] = strconv.Itoa(num) } sort.Slice(ss, func(i, j int) bool { return ss[i]+ss[j] >= ss[j]+ss[i] }) o := strings.Join(ss, "") if o[0] == '0' { return "0" } return o }