-
Notifications
You must be signed in to change notification settings - Fork 0
/
面试题 17.14. 最小K个数.java
111 lines (98 loc) · 2.5 KB
/
面试题 17.14. 最小K个数.java
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/**
* 排序
*/
class Solution {
public int[] smallestK(int[] arr, int k) {
Arrays.sort(arr); // 基于排序
int[] res = new int[k];
for(int i = 0; i < k; i++){
res[i] = arr[i];
}
return res;
}
}
/**
* 最大堆
*/
class Solution {
public int[] smallestK(int[] arr, int k) {
int[] res = new int[k];
if(k == 0){
return res;
}
// 创建最大堆
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>(){
public int compare(Integer num1, Integer num2){
return -(num1.compareTo(num2));
}
});
// O(k * logk)
for(int i = 0; i < k; i++){
pq.offer(arr[i]);
}
// O(n * logk)
for(int i = k; i < arr.length; i++){
if(arr[i] < pq.peek()){
pq.offer(arr[i]);
pq.poll();
}
}
// O(k * logk)
int idx = 0;
while(!pq.isEmpty()){
res[idx++] = pq.poll();
}
return res;
}
}
/**
* 快排
*/
class Solution {
Random rand;
public int[] smallestK(int[] arr, int k) {
rand = new Random();
quickSort(arr, 0, arr.length - 1, k); // 如果主元的位置是 k,那主元及主元之前就有 k 个最小的元素了
int[] res = new int[k];
for(int i = 0; i < k; i++){
res[i] = arr[i];
}
return res;
}
private void quickSort(int[] arr, int left, int right, int targetPos){
if(left >= right){
return;
}
int pivot = rand.nextInt(right - left) + left;
swap(arr, left, pivot);
pivot = left;
int l = left + 1;
int r = right;
while(l < r){
while(l < r && arr[l] <= arr[pivot]){
l++;
}
while(l < r && arr[r] >= arr[pivot]){
r--;
}
swap(arr, l, r);
}
if(arr[pivot] <= arr[l]){
swap(arr, l - 1, pivot);
pivot = l - 1;
}else{
swap(arr, l, pivot);
pivot = l;
}
if(pivot == targetPos){
return;
}
quickSort(arr, left, pivot - 1, targetPos);
quickSort(arr, pivot + 1, right, targetPos);
}
private void swap(int[] arr, int index1, int index2){
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
}