Saturday, April 23, 2022

Leet Code 973. K Closest Points to Origin

https://leetcode.com/problems/k-closest-points-to-origin/

Example 1:

Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].


isme ek ek kr kr point ka (0,0) se distance nikalenge and priority queue me add kr denge as max heap.
priority queue me elements sirf 'k' size ke hi rhenge, agr 'k' se jyada hote hain to remove.
At the end humare paas woh 'k' points honge jo closest hain







package pep.Day66;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class LeetCode_973_K_Closest_Points_to_Origin {
public static void main(String[] args) {
int[][] points = {{3, 3}, {5, -1}, {-2, 4}};
int k = 2;
printArr(kClosest(points, k));
}

private static void printArr(int[][] kClosest) {

for (int[] x : kClosest) {
for (int y : x) {
System.out.print(y + " ");
}
System.out.println();

}
}

public static int[][] kClosest(int[][] p, int k) {
Queue<Integer> pq1 = new PriorityQueue<>((a, b) -> {
// double d1 = Math.sqrt(p[a][0] * p[a][0] + p[a][1] * p[a][1]);
// double d2 = Math.sqrt(p[b][0] * p[b][0] + p[b][1] * p[b][1]);

double newV = Math.sqrt(p[a][0] * p[a][0] + p[a][1] * p[a][1]);
double oldV = Math.sqrt(p[b][0] * p[b][0] + p[b][1] * p[b][1]);
return (int) (oldV - newV);
});

Queue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
Integer newV = p[a][0] * p[a][0] + p[a][1] * p[a][1];
Integer oldV = p[b][0] * p[b][0] + p[b][1] * p[b][1];
//return (int) (oldV - newV); -> max Heap
//return (int) (newV - oldV); -> min Heap
return oldV.compareTo(newV);
}
});


for (int i = 0; i < p.length; i++) {
pq.add(i);
if (pq.size() > k)
pq.remove();
}

int idx = 0, ans[][] = new int[k][2];
while (!pq.isEmpty())
ans[idx++] = p[pq.remove()];

return ans;
}
}



No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...