-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path30.最小的K个数.cpp
More file actions
34 lines (31 loc) · 962 Bytes
/
30.最小的K个数.cpp
File metadata and controls
34 lines (31 loc) · 962 Bytes
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
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
if (input.size() == 0 || input.size() < k || k <= 0)
return {};
int pos = partion(input, 0, input.size() - 1);
while (pos != k - 1)
{
if (pos > k - 1)
pos = partion(input, 0, pos - 1);
else
pos = partion(input, pos + 1, input.size() - 1);
}
vector<int> res(input.begin(), input.begin() + k);
return res;
}
private:
int partion(vector<int>& input, int begin, int end)
{
int key = input[begin];
while (begin < end)
{
while (begin < end && input[end] >= key) --end;
input[begin] = input[end];
while (begin < end && input[begin] < key) ++begin;
input[end] = input[begin];
}
input[begin] = key;
return begin;
}
};