-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkClosestPoints.cpp
More file actions
55 lines (53 loc) · 1.64 KB
/
kClosestPoints.cpp
File metadata and controls
55 lines (53 loc) · 1.64 KB
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
// Easiest solution using partition_sort
bool comp (vector<int> &a, vector<int> &b) {
return a[0]*a[0]+a[1]*a[1]<b[0]*b[0]+b[1]*b[1];
}
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
partition_sort(points.begin(), points.begin()+k, points.end(), comp);
return vector<vector<int>>(points.begin(), points.begin()+k);
}
// Naive solution which will not run in end_time
/*
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
vector<int>dist;
vector<vector<int>>pos;
int ctr = 0;
int currDist;
for (int i=0; i<points.size(); i++) {
currDist = points[i][0]*points[i][0]+points[i][1]*points[i][1];
if (ctr == 0) {
dist.push_back(currDist);
pos.push_back(points[i]);
ctr++;
}
else {
if (ctr == k) {
if (currDist<dist[k-1]) {
// pop off and insert
dist.pop_back();
pos.pop_back();
--ctr;
}
}
if(ctr<k) {
int flag = 0;
for (int j=0; j<ctr; j++) {
if(currDist<dist[j]){
dist.insert(dist.begin()+j, currDist);
pos.insert(pos.begin()+j, points[i]);
ctr++;
flag = 1;
break;
}
}
if(flag!=1) {
dist.push_back(currDist);
pos.push_back(points[i]);
ctr++;
}
}
}
}
return pos;
}
*/