-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetCode.cpp
69 lines (58 loc) · 1.23 KB
/
LeetCode.cpp
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
#include "Solution.h"
#include<string.h>
#include <set>
#include<vector>
#include<iostream>
#include<map>
#include<stack>
using namespace std;
int distance(const vector<int> &p) {
return p[0] * p[0] + p[1] * p[1];
}
// [low, high]
int partition(vector<vector<int>>& points, int low, int high) {
auto pivot = high;
auto next = low;
using std::swap;
for (; low < high; low++) {
int distLow = distance(points[low]);
int disHigh = distance(points[high]);
if (distLow < disHigh)
{
swap(points[low], points[next++]);
}
}
swap(points[pivot], points[next]);
return next;
}
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
if (points.size() < K) {
return vector<vector<int>>();
}
int mid;
int low = 0, high = points.size() - 1;
while ((mid = partition(points, low, high)) != K-1) {
if (mid < K-1) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return vector<vector<int>>(points.begin(), points.begin() + K);
}
int main9()
{
vector<vector<int>> pos;
vector<int> vec1, vec2, vec3;
vec1.push_back(3);
vec1.push_back(3);
vec2.push_back(2);
vec2.push_back(-1);
vec3.push_back(2);
vec3.push_back(4);
pos.push_back(vec1);
pos.push_back(vec2);
pos.push_back(vec3);
kClosest(pos,1);
return 0;
}