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]]

Approach

Java


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class KClosestPointsToOrigin {
    public static void main(String[] args) {
        int[][] points = { { 13 }, { -22 } };
        int K = 1;
        int[][] point = kClosest(points, K);
        System.out.println(Arrays.deepToString(point));
    }

    static int[][] kClosest(int[][] pointsint K) {
        List<int[]> res = new ArrayList<int[]>();
        List<Pairmyvec = new ArrayList<Pair>();
        for (int[] i : points) {
            int x = i[0] * i[0] + i[1] * i[1];
            Pair m = new Pair(x, i);
            myvec.add(m);
        }
        Collections.sort(myvec);
        for (int i = 0; i < K; i++)
            res.add(myvec.get(i).getSecond());
        return res.toArray(new int[0][2]);
    }

    static class Pair implements Comparable<Pair> {
        private Integer first;
        private int[] second;

        public Integer getFirst() {
            return first;
        }

        public void setFirst(Integer first) {
            this.first = first;
        }

        public int[] getSecond() {
            return second;
        }

        public void setSecond(int[] second) {
            this.second = second;
        }

        public Pair(Integer firstint[] second) {
            super();
            this.first = first;
            this.second = second;
        }

        @Override
        public int compareTo(Pair o) {
            return first - o.getFirst();
        }
    }
}

C++

#include <bits/stdc++.h>
using namespace std;


vector<vector<int>> kClosest(vector<vector<int>>& pointsint K
{
        vector<vector<int>> res;
        int n=points.size();
        vectorpair<intvector<int> >> myvec
        for(auto i:points)
        {
            int x=i[0]*i[0]+i[1]*i[1];
            myvec.push_back(make_pair(x,i));
        }
        sort(myvec.begin(),myvec.end());
        for(int i=0;i<K;i++)
              res.push_back(myvec[i].second);
        return res;
}

int main()
{
    vector<vector<int>> points ={{1,3},{-2,2}};
    int  K = 1;
    vector<vector<int>> pointkClosest(points,K);
    cout<<"[";
    for(int i=0;i<point.size();i++)
      {
          cout<<"[";
          for(int j=0;j<point[i].size();j++)
           {
               cout<<point[i][j];
               if(j!=point[i].size()-1)
                 cout<<",";
           }
         cout<<"]";
          if(i!=point.size()-1)
            cout<<",";
      }
    cout<<"]";
    return 0;
}


No comments:

Post a Comment