|
| 1 | +//Both solutions use same Idea |
| 2 | +//Time complexity O(Nlogk) |
| 3 | + |
| 4 | +classSolution { |
| 5 | +publicint[][]kClosest(int[][]points,intk) { |
| 6 | +HashMap<int[],Double>map =newHashMap<>(); |
| 7 | +PriorityQueue<Map.Entry<int[],Double>>pq =newPriorityQueue<>((a,b)->Double.compare(a.getValue(),b.getValue())); |
| 8 | +for (inti =0;i<points.length;i++) { |
| 9 | +map.put(points[i],Math.pow((Math.pow(points[i][0],2)+Math.pow(points[i][1],2)),0.5));//We can also ignore this rooting as I did in the next solution |
| 10 | + } |
| 11 | +for (Map.Entryset:map.entrySet()) { |
| 12 | +pq.add(set); |
| 13 | + } |
| 14 | +int[][]ans =newint[k][2]; |
| 15 | +for (inti =0;i<k;i++) { |
| 16 | +int[]temp =pq.poll().getKey(); |
| 17 | +ans[i][0] =temp[0]; |
| 18 | +ans[i][1] =temp[1]; |
| 19 | + } |
| 20 | +returnans; |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +//Since, we need to find the minimum, it doens't matter if we square root them. As the minimum will remain the same after square rooting also. |
| 25 | +//Ex: 4.8<4.9 -> root(4.8)<root(4.9) |
| 26 | + |
| 27 | +classSolution { |
| 28 | +publicint[][]kClosest(int[][]points,intk) { |
| 29 | +HashMap<int[],Integer>map =newHashMap<>(); |
| 30 | +PriorityQueue<Map.Entry<int[],Integer>>pq =newPriorityQueue<>((a,b)->a.getValue()-b.getValue()); |
| 31 | +for (inti =0;i<points.length;i++) { |
| 32 | +map.put(points[i], (int)(Math.pow(points[i][0],2)+Math.pow(points[i][1],2))); |
| 33 | + } |
| 34 | +for (Map.Entryset:map.entrySet()) { |
| 35 | +pq.add(set); |
| 36 | + } |
| 37 | +int[][]ans =newint[k][2]; |
| 38 | +for (inti =0;i<k;i++) { |
| 39 | +int[]temp =pq.poll().getKey(); |
| 40 | +ans[i][0] =temp[0]; |
| 41 | +ans[i][1] =temp[1]; |
| 42 | + } |
| 43 | +returnans; |
| 44 | + } |
| 45 | +} |