0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Leetcode Medium 973. K Closest Points to Origin

Posted at

各地点のうち(0,0)から最も近い地点を求める

-それぞれ距離を計算する(sqrtは求めなくてよい)
-結果をソートして小さい方から順に表示する

class Solution {
public:
    vector<vector<int>> kClosest(vector<vector<int>>& p, int k) {
        vector<pair<int, vector<int>>> distance;
        for (auto v : p) {
            distance.push_back({ v[0] * v[0] + v[1] * v[1], v });
        }
        sort(distance.begin(), distance.end());

        vector<vector<int>> ans;


        for(int i = 0;i<distance.size();i++){
            if (i >= k)break;
            ans.push_back(distance[i].second);
        }

        return ans;
    }
};

//int main()
//{
//    Solution* Sol = new Solution();
//    random_device rnd;
//    mt19937 mt(rnd());
//
//    //vector<vector<int>> v1 = { {1,3},{-2,2} };
//    //int k = 1;
//
//    vector<vector<int>> v1 = { {3,3},{5,-1},{-2,4} };
//    int k = 2;
//
//    //v1.push_back(15);
//    //for (int i = 0; i < 100; ++i) v1.push_back(mt() % 1000);
//
//    Sol->kClosest(v1,2);
//}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?