https://chat.openai.com/share/2a5df089-6b4a-4b66-94e0-04c025860a89
Minheap: Smallest element on top
Maxheap: Largest element on top
priority_queue<int, vector<int>, greater<int>> minHeap;
priority_queue<int, vector<int>, less<int>> maxHeap;
from k closest points to origin:
std::move is better than simply copying or push_back in terms of both runtime and memory.
std::nth_element vs. partial sort vs. sort
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
auto distance = [&](vector<int> x) {
int dis = 0 ;
dis += (x[0]*x[0] + x[1]*x[1]);
return dis;
};
vector<pair<int,int>> hashmap(points.size());
for(int i = 0 ; i < points.size(); i++){
auto dist = distance(points[i]);
hashmap[i] = {dist, i};
}
std::ranges::nth_element(hashmap, std::next(hashmap.begin(), k));
//Gives you the correct nth_element without sorting the whole container
//{4,5,10,1,2,3,7} n = 3
//{4,5,3,10,1,2,7}
vector<vector<int>> ans(k);
for(int i = 0 ; i < k; i++){
ans[i] = std::move(points[hashmap[i].second]);
//instead of copying it "moves" the item
}
return ans;
}
};