Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. Input: points = [[1,3],[-2,2]], K = 1
  2. Output: [[-2,2]]
  3. Explanation:
  4. The distance between (1, 3) and the origin is sqrt(10).
  5. The distance between (-2, 2) and the origin is sqrt(8).
  6. Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
  7. We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].
  8.  
  9. Input: points = [[3,3],[5,-1],[-2,4]], K = 2
  10.  
  11. public class KClosestPointsToOrigin {
  12.  
  13. public int[][] kClosest(int[][] points, int K) {
  14.  
  15. int rows = points.length;
  16.  
  17.  
  18. SortedMap<Double, List<CoordinatePoint>> distanceToPoint = new TreeMap<>();
  19.  
  20. for(int i =0; i<rows; i++) {
  21. double distance = getDistance(points[i]);
  22. if(Objects.nonNull(distanceToPoint.get(distance))) {
  23. List<CoordinatePoint> coordinatePointList = distanceToPoint.get(distance);
  24. coordinatePointList.add(new CoordinatePoint(points[i][0], points[i][1]));
  25. } else {
  26. List<CoordinatePoint> coordinatePoints = new ArrayList<>();
  27. coordinatePoints.add(new CoordinatePoint(points[i][0], points[i][1]));
  28. distanceToPoint.put(distance, coordinatePoints);// x and y coordinates.
  29. }
  30. }
  31.  
  32. int[][] arrayToReturn = new int[K][2];
  33. int counter = 0;
  34. for (Double key : distanceToPoint.keySet()) {
  35. List<CoordinatePoint> coordinatePoints = distanceToPoint.get(key);
  36. Iterator iterator1 = coordinatePoints.iterator();
  37. while (iterator1.hasNext() && counter < K) {
  38. CoordinatePoint coordinatePoint = (CoordinatePoint) iterator1.next();
  39. arrayToReturn[counter][0] = coordinatePoint.x;
  40. arrayToReturn[counter][1] = coordinatePoint.y;
  41. counter++;
  42. }
  43. }
  44.  
  45. return arrayToReturn;
  46. }
  47.  
  48. private double getDistance(int[] point) {
  49. int x = point[0];
  50. int y = point[1];
  51.  
  52. int x2 = Math.abs(x) * Math.abs(x);
  53. int y2 = Math.abs(y) * Math.abs(y);
  54.  
  55. return Math.sqrt(x2+y2);
  56. }
  57.  
  58. public CoordinatePoint(int x, int y) {
  59. this.x = x;
  60. this.y = y;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement