题目描述如下:
1562. Number of restaurants
Give a List of data representing the coordinates[x,y] of each restaurant and the customer is at the origin[0,0]. Find the n restaurants closest to the customer firstly. Then you need to pick n restaurants which appeare firstly in the List and the distance between the restaurant and the customer can’t more than the longest distance in the n closest restaurants. Return their coordinates in the original order.
Example
Given : n = 2 , List = [[0,0],[1,1],[2,2]]
Return : [[0,0],[1,1]]
Given : n = 3,List = [[0,1],[1,2],[2,1],[1,0]]
Return :[[0,1],[1,2],[2,1]]
Notice
1.Coordinates in range [-1000,1000]
2.n>0
3.No same coordinates
这题实际上就是求N个无序数中的最小的n个数,所以用最大堆。
堆的大小为n。遍历完后取堆top,然后再遍历一遍,列出最先的n个比top小的数。
struct Node {
int x;
int y;
Node(int vx = 0, int vy = 0) : x(vx), y(vy) {}
long long distance(const Node & a, const Node & b) const {
return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
}
bool operator < (const Node &n) const {
return distance(const_cast<Node &>(*this), Node(0,0)) < distance(n, Node(0,0));
}
bool operator == (const Node &n) const {
return distance(const_cast<Node &>(*this), Node(0,0)) == distance(n, Node(0,0));
}
};
class Solution {
public:
/**
* @param restaurant:
* @param n:
* @return: nothing
*/
vector<vector<int> > nearestRestaurant(vector<vector<int> > &restaurant, int n) {
int nRow = restaurant.size();
vector<vector<int> > result;
if ((nRow < n) || (n == 0)) return result;
Node x;
for (int i = 0; i < nRow; ++i) {
if (i < n) {
maxHeap.push(Node(restaurant[i][0], restaurant[i][1]));
} else {
x = maxHeap.top();
if (Node(restaurant[i][0], restaurant[i][1]) < x) {
maxHeap.pop();
maxHeap.push(Node(restaurant[i][0], restaurant[i][1]));
}
}
}
Node topn = maxHeap.top();
for (int i = 0; i < nRow; ++i) {
if ((Node(restaurant[i][0], restaurant[i][1]) < topn) ||
(Node(restaurant[i][0], restaurant[i][1]) == topn)) {
vector<int> temp;
temp.push_back(restaurant[i][0]);
temp.push_back(restaurant[i][1]);
result.push_back(temp);
}
}
return result;
}
private:
// priority_queue<Node, vector<Node>, greater<Node> > minHeap;
priority_queue<Node> maxHeap;
};