I need to make a Solution class that holds several 1D points and it can be given a center and a number k to calculated the k nearest points to this center.
My code,
class Solution {
private:
int center_;
struct Point {
int x;
bool operator<(const Point &other) const {
return (x - center_) * (x - center_) < (other.x - center_) * (other.x - center_);
}
};
public:
vector<int> findNearestKPoints(vector<int> &nums, int k, int center) {
center_ = center;
// vetor<int> to vector<Point>
vector<Point> points;
for (int num : nums) {
points.push_back({num});
}
// partition vector<Point>
nth_element(points.begin(), points.begin() + k - 1, points.end(), less<int>());
// vector<Point> to vector<int>
vector<int> res;
for (int i = 0; i < k; ++i) {
const Point &point = points[i];
res.push_back(point.val);
}
return res;
}
}
but it cannot compile.
The compile error is
use of non-static data member 'center_' of 'Solution' from nested type 'Point'
So how to fix it? Maybe there are other ways to calculate nearest points.
Aucun commentaire:
Enregistrer un commentaire