forked from geekxh/hello-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
56 lines (51 loc) · 1.39 KB
/
Solution.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
import java.util.ArrayList;
/**
* @author Anonymous
* @since 2019/12/6
*/
public class Solution {
/**
* 获取数组中最小的k个数
*
* @param input 输入的数组
* @param k 元素个数
* @return 最小的k的数列表
*/
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList<Integer> res = new ArrayList<>();
if (input == null || input.length == 0 || input.length < k || k < 1) {
return res;
}
int n = input.length;
int start = 0, end = n - 1;
int index = partition(input, start, end);
while (index != k - 1) {
if (index > k - 1) {
end = index - 1;
} else {
start = index + 1;
}
index = partition(input, start, end);
}
for (int i = 0; i < k; ++i) {
res.add(input[i]);
}
return res;
}
private int partition(int[] input, int start, int end) {
int index = start - 1;
for (int i = start; i < end; ++i) {
if (input[i] < input[end]) {
swap(input, i, ++index);
}
}
++index;
swap(input, index, end);
return index;
}
private void swap(int[] array, int i, int j) {
int t = array[i];
array[i] = array[j];
array[j] = t;
}
}