Update 数组相关.md

master
Omooo 5 years ago
parent 526047e496
commit d145d689c2
  1. 52
      blogs/Algorithm/剑指 Offer/数组相关.md

@ -159,3 +159,55 @@ class Solution {
}
```
[45. 把数组排成最小的数](https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/)
```java
class Solution {
public String minNumber(int[] nums) {
String[] strings = getStringArray(nums);
Arrays.sort(strings, new Cop());
StringBuilder result = new StringBuilder();
for (String s : strings) {
result.append(s);
}
return result.toString();
}
private String[] getStringArray(int[] nums) {
String[] strings = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
strings[i] = String.valueOf(nums[i]);
}
return strings;
}
class Cop implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
String s1 = o1 + o2;
String s2 = o2 + o1;
return s1.compareTo(s2);
}
}
}
```
```java
class Solution {
public String minNumber(int[] nums) {
String[] strings = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
strings[i] = String.valueOf(nums[i]);
}
Arrays.sort(strings, (o1, o2) -> (o1 + o2).compareTo(o2 + o1));
StringBuilder result = new StringBuilder();
for (String s : strings) {
result.append(s);
}
return result.toString();
}
}
```

Loading…
Cancel
Save