class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
vector<vector<int>> result;
map<double, vector<int>, greater<int>> rMap;
for (int i = 0; i < points.size(); i++) {
int num = ((points[i][0])*(points[i][0])) + ((points[i][1])*(points[i][1]));
double temp = sqrt(num);
if (rMap.size() < K) {
rMap.insert(pair<double, vector<int>>(temp, points[i]));
}
else {
map<double, vector<int>>::iterator it = rMap.begin();
if (it->first > temp) {
// rMap size seems to be fine
rMap.erase(rMap.find(it->first));
//rMap size still seems to be fine
rMap.insert(pair<double, vector<int>>(temp, points[i]));
// rMap size is the same as before the insert
// new pair is also not inserted
}
}
}
for (map<double, vector<int>>::iterator it = rMap.begin(); it != rMap.end(); it++) {
result.push_back(it->second);
}
return result;
}
};
我做了一些内联评论。为什么map :: insert不在此处将元素添加到地图?我不是在寻找替代解决方案。我只想知道该行为的原因。
这不起作用:
您的输入:[[3,3],[5,-1],[-2,4]] 2
输出:[[3,3]]
预期:[[3,3],[-2,4]]
但这可行: 您的输入:[[68,97],[34,-84],[60,100],[2,31],[-27,-38],[-73,-74],[-55,-39] ,[62,91],[62,92],[-57,-67]] 5
输出:[[34,-84],[-57,-67],[-55,-39],[-27,-38],[2,31]]
预期:[[2,31],[-27,-38],[-55,-39],[-57,-67],[34,-84]]