-
Notifications
You must be signed in to change notification settings - Fork 0
/
k_closest_points.cpp
81 lines (74 loc) · 2.34 KB
/
k_closest_points.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
75
76
77
78
79
80
81
/*
* =====================================================================================
*
* Filename: k_closest_points.cpp
*
* Description: 973. K Closest Points to Origin.
* https://leetcode.com/problems/k-closest-points-to-origin/
*
* Version: 1.0
* Created: 02/20/2023 19:40:46
* Revision: none
* Compiler: gcc
*
* Author: [email protected]
* Organization:
*
* =====================================================================================
*/
#include <algorithm>
#include <queue>
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using std::priority_queue;
using std::vector;
// Sorting
class Solution1 {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
std::partial_sort(
points.begin(), points.begin() + k, points.end(),
[](const vector<int>& a, const vector<int>& b) {
return ((a[0] * a[0] + a[1] * a[1]) < (b[0] * b[0] + b[1] * b[1]));
});
return {points.begin(), points.begin() + k};
}
};
// Max heap
class Solution2 {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
priority_queue<vector<int>, vector<vector<int>>, Compare> pq(points.begin(),
points.end());
while (pq.size() > k) {
pq.pop();
}
vector<vector<int>> res;
while (!pq.empty()) {
res.push_back(pq.top());
pq.pop();
}
return res;
}
struct Compare {
bool operator()(const vector<int>& a, const vector<int>& b) {
return ((a[0] * a[0] + a[1] * a[1]) < (b[0] * b[0] + b[1] * b[1]));
}
};
};
TEST(Solution, kClosest) {
vector<std::tuple<vector<vector<int>>, int, vector<vector<int>>>> cases = {
std::make_tuple(vector<vector<int>>{{1, 3}, {-2, 2}}, 1,
vector<vector<int>>{{-2, 2}}),
std::make_tuple(vector<vector<int>>{{3, 3}, {5, -1}, {-2, 4}}, 2,
vector<vector<int>>{{3, 3}, {-2, 4}}),
};
for (auto& c : cases) {
EXPECT_THAT(Solution1().kClosest(std::get<0>(c), std::get<1>(c)),
testing::ElementsAreArray(std::get<2>(c)));
EXPECT_THAT(Solution2().kClosest(std::get<0>(c), std::get<1>(c)),
testing::UnorderedElementsAreArray(std::get<2>(c)));
}
}