Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
k-closest-points-to-origin.cpp 1.36 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2019-01-13 17:21 +08:00 . Update k-closest-points-to-origin.cpp
// Time: O(n) on average
// Space: O(1)
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
static const auto& dist = [](const vector<int>& v) {
return v[0] * v[0] + v[1] * v[1];
};
nth_element(points.begin(), points.begin() + K, points.end(),
[&](const vector<int>& a, const vector<int>& b) {
return dist(a) < dist(b);
});
return {points.cbegin(), points.cbegin() + K};
}
};
// Time: O(nlogk)
// Space: O(k)
class Solution2 {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
static const auto& dist = [](const vector<int>& v) {
return v[0] * v[0] + v[1] * v[1];
};
struct Compare {
bool operator()(const vector<int>& a, const vector<int>& b) {
return dist(a) < dist(b);
}
};
priority_queue<vector<int>, vector<vector<int>>, Compare> max_heap;
for (const auto& point : points) {
max_heap.emplace(point);
if (max_heap.size() > K) {
max_heap.pop();
}
}
vector<vector<int>> result;
while (!max_heap.empty()) {
result.emplace_back(max_heap.top()), max_heap.pop();
}
return result;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助