public String largestNumber(int[] nums){ String[] strArr = new String[nums.length]; for (int i = 0; i < strArr.length; i++) { strArr[i] = String.valueOf(nums[i]); }
Arrays.sort(strArr, (o1, o2) -> (int) (Long.parseLong(o1 + o2) - Long.parseLong(o2 + o1))); //就这句,这里的o1 + o2是字符串拼接 StringBuilder sb = new StringBuilder(); boolean flag = true; for(int i = strArr.length - 1; i >= 0; i--){ sb.append(strArr[i]); if (!"0".equals(strArr[i])) flag = false; } if (flag) return"0"; return sb.toString(); }
或者直接调用字符串的compareTo方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public String largestNumber(int[] nums){ String[] strArr = new String[nums.length]; for (int i = 0; i < strArr.length; i++) { strArr[i] = String.valueOf(nums[i]); }
Arrays.sort(strArr, (o1, o2) -> (o1 + o2).compareTo(o2 + o1)); StringBuilder sb = new StringBuilder(); boolean flag = true; for(int i = strArr.length - 1; i >= 0; i--){ sb.append(strArr[i]); if (!"0".equals(strArr[i])) flag = false; } if (flag) return"0"; return sb.toString(); }