179-最大数

179-最大数

力扣179

https://leetcode-cn.com/problems/largest-number/

害,网易的题没做出来,还是牛客原题,是一道字符串问题,字符串拼接后保证数最大,考的是sort的重写Comparator

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) -> (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();
}

其他字符串类型的题目可以点击这里

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×