LeetCode K Closest Points to Origin

973. K Closest Points to Origin

We have a list of points on the plane.  Find the K closest points to the origin (0, 0).

(Here, the distance between two points on a plane is the Euclidean distance.)

You may return the answer in any order.  The answer is guaranteed to be unique (except for the order that it is in.)

Example 1:

Input: points = [[1,3],[-2,2]], K = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].


Example 2:

Input: points = [[3,3],[5,-1],[-2,4]], K = 2
Output: [[3,3],[-2,4]]
(The answer [[-2,4],[3,3]] would also be accepted.)


Note:

1. 1 <= K <= points.length <= 10000
2. -10000 < points[i][0] < 10000
3. -10000 < points[i][1] < 10000

1.先排序（快排）时间复杂度为nlogn
2.建堆，堆的大小为K，建立大根堆或者小根堆，时间复杂度为nlogK(如果要求出前K个较大的，那么就建立小根堆，一旦比堆顶大，那么就入堆)；
3.结合快速排序划分的方法，不断减小问题的规模

class Solution {
private:
vector<int> origin;

int CalDist(vector<int> &p1, vector<int> &p2) {
return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);
}

void MySwap(vector<vector<int>>& points, int u, int v) {
swap(points[u][0], points[v][0]);
swap(points[u][1], points[v][1]);
}

void Work(vector<vector<int>>& points, int l, int r, int K) {
if (l >= r) return;

int pivot = r;
int pdist = CalDist(points[pivot], origin);
int i = l;
for (int j = l; j < r; ++j) {
int idist = CalDist(points[j], origin);
if (idist < pdist) {
MySwap(points, i++, j);
}
}
MySwap(points, i, pivot);

if (K == i)return;
else if (K < i)Work(points, l, i - 1, K);
else Work(points, i + 1, r, K);
}
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
origin = { 0, 0 }; // 求与该点距离最近的top-k个点，本题中该点是原点

for (int i = 0; i < points.size(); ++i) {
printf("x=%d,y=%d,dist=%d\n", points[i][0], points[i][1], CalDist(points[i], origin));
}

Work(points, 0, points.size() - 1, K - 1);

vector<vector<int>> ans;
for (int i = 0; i < K; ++i) ans.push_back(points[i]);
return ans;
}
};