1985. Find the Kth Largest Integer in the Array

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
53
54
55
56
57
58
59
60
class Solution {
public String kthLargestNumber(String[] nums, int k) {
int targetIndex = k - 1;

int left = 0, right = nums.length - 1;
while (true) {
int pivotIndex = partition(nums, left, right);
if (pivotIndex < targetIndex) {
left = pivotIndex + 1;
} else if (pivotIndex > targetIndex) {
right = pivotIndex - 1;
} else {
return nums[targetIndex];
}
}
}

private int partition(String[] nums, int left, int right) {
int randomIndex = left + ThreadLocalRandom.current().nextInt(right - left + 1);
swap(nums, left, randomIndex);
String pivotValue = nums[left];

// 从大到小排序
int i = left, j = right;
while (i < j) {
while (i < j && lessThanOrEquals(nums[j], pivotValue)) {
j--;
}
while (i < j && greatThanOrEquals(nums[i], pivotValue)) {
i++;
}
swap(nums, i, j);
}

swap(nums, left, i);
return i;
}

private boolean greatThanOrEquals(String numA, String numB) {
if (numA.length() == numB.length()) {
return numA.compareTo(numB) >= 0;
}

return numA.length() > numB.length();
}

private boolean lessThanOrEquals(String numA, String numB) {
if (numA.length() == numB.length()) {
return numA.compareTo(numB) <= 0;
}

return numA.length() < numB.length();
}

private void swap(String[] nums, int i, int j) {
String tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}

References

1985. Find the Kth Largest Integer in the Array