From 95c2c09d5e0b1167580ea4cbaa62efba1492a720 Mon Sep 17 00:00:00 2001 From: Abhishek Tripathi <42455093+abhishektripathi66@users.noreply.github.com> Date: Mon, 28 Oct 2024 20:02:52 +0530 Subject: [PATCH] Create KClosestPointstoOrigin.java --- Leetcode/KClosestPointstoOrigin.java | 86 ++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 Leetcode/KClosestPointstoOrigin.java diff --git a/Leetcode/KClosestPointstoOrigin.java b/Leetcode/KClosestPointstoOrigin.java new file mode 100644 index 0000000..2f12f48 --- /dev/null +++ b/Leetcode/KClosestPointstoOrigin.java @@ -0,0 +1,86 @@ +/** +973. K Closest Points to Origin +Solved +Medium +Topics +Companies +Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). + +The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). + +You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). + + **/ +/** Mys soluion */ +class Solution { + public int[][] kClosest(int[][] points, int k) { + double[][] a = new double[points.length][2]; + int[][] out = new int[k][2]; + for(int i=0;iDouble.compare(a[0],b[0])); + } + + public double findDistance(int[] a){ + return Math.pow(Math.pow(a[0],2)+Math.pow(a[1],2),0.5); + } +} + +/** best solution */ +class Solution { + public int[][] kClosest(int[][] points, int k) { + int smallestK = quickSelect(points, 0, points.length - 1, k); + return Arrays.copyOfRange(points, 0, smallestK); + } + + private int quickSelect(int[][] points, int left, int right, int k) { + if (left >= right) { + return k; + } + int l = left, r = right; + int pivotIdx = left + (right - left)/2; + int pivotDist = getDist(points[pivotIdx]); + + while (l <= r) { + while (l <= r && getDist(points[l]) < pivotDist) { + l++; + } + while (l <= r && getDist(points[r]) > pivotDist) { + r--; + } + + if (l <= r) { + swap(points, l++, r--); + } + } + + if (k <= r) { + return quickSelect(points, left, r, k); + } + + return quickSelect(points, l, right, k); + } + + private void swap(int[][] points, int i, int j) { + int[] tmp = points[i]; + points[i] = points[j]; + points[j] = tmp; + } + + private int getDist(int[] point) { + return point[0] * point[0] + point[1] * point[1]; + } +}