forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0973-k-closest-points-to-origin.cpp
74 lines (63 loc) · 2.07 KB
/
0973-k-closest-points-to-origin.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
70
71
72
73
74
/*
Given array of points & an int k, return k closest points to (0, 0)
Ex. points = [[1,3],[-2,2]], k = 1 -> [[-2,2]]
Quickselect, partition until pivot = k, left side all < k
Time: O(n) -> optimized from O(n log k) max heap solution
Space: O(1)
*/
// class Solution {
// public:
// vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
// priority_queue<pair<double, vector<int>>> pq;
// for (int i = 0; i < points.size(); i++) {
// double distance = sqrt(pow(points[i][0], 2) + pow(points[i][1], 2));
// pq.push({distance, points[i]});
// if (pq.size() > k) {
// pq.pop();
// }
// }
// vector<vector<int>> result;
// while(!pq.empty()) {
// result.push_back(pq.top().second);
// pq.pop();
// }
// return result;
// }
// };
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
int low = 0;
int high = points.size() - 1;
int pivotIndex = points.size();
while (pivotIndex != k) {
pivotIndex = partition(points, low, high);
if (pivotIndex < k) {
low = pivotIndex;
} else {
high = pivotIndex - 1;
}
}
return vector<vector<int>>(points.begin(), points.begin() + k);
}
private:
int partition(vector<vector<int>>& points, int low, int high) {
vector<int> pivot = points[low + (high - low) / 2];
int pivotDistance = getDistance(pivot);
while (low < high) {
if (getDistance(points[low]) >= pivotDistance) {
swap(points[low], points[high]);
high--;
} else {
low++;
}
}
if (getDistance(points[low]) < pivotDistance) {
low++;
}
return low;
}
int getDistance(vector<int>& point) {
return pow(point[0], 2) + pow(point[1], 2);
}
};