咱們有一個由平面上的點組成的列表 points。須要從中找出 K 個距離原點 (0, 0) 最近的點。code
(這裏,平面上兩點之間的距離是歐幾里德距離。)io
你能夠按任何順序返回答案。除了點座標的順序以外,答案確保是惟一的。class
示例 1:sort
輸入:points = [[1,3],[-2,2]], K = 1 輸出:[[-2,2]] 解釋: (1, 3) 和原點之間的距離爲 sqrt(10), (-2, 2) 和原點之間的距離爲 sqrt(8), 因爲 sqrt(8) < sqrt(10),(-2, 2) 離原點更近。 咱們只須要距離原點最近的 K = 1 個點,因此答案就是 [[-2,2]]。di
示例 2:poi
輸入:points = [[3,3],[5,-1],[-2,4]], K = 2 輸出:[[3,3],[-2,4]] (答案 [[-2,4],[3,3]] 也會被接受。)co
提示:push
想複雜的一種作法結構體
struct PointNode { vector<int> v; double dis; PointNode(int x, int y) { v.push_back(x); v.push_back(y); dis = sqrt(x* x + y * y); } }; bool cmp(PointNode x, PointNode y) { return x.dis < y.dis; } class Solution { public: vector<vector<int>> kClosest(vector<vector<int>>& points, int K) { vector<PointNode> v; vector<vector<int> > ans; for (int i = 0; i < points.size(); i++) { v.push_back(PointNode(points[i][0], points[i][1])); } sort(v.begin(), v.end(), cmp); for (int i = 0; i < K; i++) { ans.push_back(v[i].v); } return ans; } };
題目簡單,不須要用到結構體return
bool cmp(vector<int> x, vector<int> y) { return x[0] * x[0] + x[1] * x[1] < y[0] * y[0] + y[1] * y[1]; } class Solution { public: vector<vector<int>> kClosest(vector<vector<int>>& points, int K) { vector<vector<int> > ans; sort(points.begin(), points.end(), cmp); for (int i = 0; i < K; i++) { ans.push_back(points[i]); } return ans; } };