把数组排成最小数

题目

https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public String minNumber(int[] nums) {
int[] number = nums;
if (number == null || number.length == 0) {
return new String();
}
String[] strNumber = new String[number.length];
for (int i=0; i<number.length; i++) {
strNumber[i] = String.valueOf(number[i]);
}
// 快排
quickSort(strNumber, 0, strNumber.length-1);
// 结果转换
StringBuilder res = new StringBuilder();
for (String str : strNumber) {
res.append(str);
}
return res.toString();
}

void quickSort(String[] strNumber, int start, int end) {
if (start >= end ) return;
int index = partition(strNumber, start, end);
if (index > start) {
quickSort(strNumber, start, index-1);
}
if (index < end) {
quickSort(strNumber, index+1, end);
}
}

int partition(String[] strNumber, int start, int end) {

int left = start;
int right = end;
String temp = strNumber[left];
while (left < right) {
while (left < right && ((strNumber[right]+strNumber[left]).compareTo(strNumber[left]+strNumber[right]))>=0) {
right--;
}
while (left < right && ((strNumber[left]+strNumber[right]).compareTo(strNumber[right]+strNumber[left]) <= 0)) {
left++;
}
temp = strNumber[left];
strNumber[left] = strNumber[right];
strNumber[right] = temp;
}
strNumber[left] = temp;
return left;

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 方法二
public String minNumber(int[] nums) {
String[] strs = new String[nums.length];
for(int i=0; i<nums.length; i++) {
strs[i] = String.valueOf(nums[i]);
}
// 快排
Arrays.sort(strs, (x, y)->(x+y).compareTo(y+x));
StringBuilder res = new StringBuilder();
for(String str : strs) {
res.append(str);
}
return res.toString();

}
Your browser is out-of-date!

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

×