-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update 0973-k-closest-points-to-origin.cs
- Loading branch information
1 parent
f1f6e7b
commit db263fc
Showing
1 changed file
with
16 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,44 +1,21 @@ | ||
public class Solution { | ||
// Closest to origin minHeap | ||
private PriorityQueue<int[], double> pq; | ||
private int size; | ||
// T: O(Max(M, KLogM)), S: O(k) | ||
public int[][] KClosest(int[][] points, int k) { | ||
pq = new PriorityQueue<int[], double>(); | ||
size = k; | ||
|
||
AddToPriorityQueue(points); | ||
|
||
return Closest(); | ||
} | ||
|
||
public class MaxHeap : IComparer<double>{ | ||
public int Compare(double x, double y){ | ||
if( x< y) return 1;å | ||
else if (x > y) return -1; | ||
else return 0; | ||
} | ||
} | ||
|
||
// T: O(M) | ||
private void AddToPriorityQueue(int[][] points){ | ||
foreach(var point in points){ | ||
//var value = (double) Math.Sqrt(point[0]*point[0] + point[1]*point[1]); | ||
var value = (double) point[0]*point[0] + point[1]*point[1]; | ||
pq.Enqueue(point, value); | ||
|
||
|
||
} | ||
} | ||
|
||
// T: O(KLogM) | ||
private int[][] Closest(){ | ||
var result = new List<int[]>(); | ||
while(size > 0){ | ||
result.Add(pq.Dequeue()); | ||
size--; | ||
var items = points.Select(point => { | ||
long x = point[0]; | ||
long y = point[1]; | ||
|
||
return (point, x * x + y * y); | ||
}); | ||
|
||
int[][] result = new int[k][]; | ||
// T: O(n) | ||
PriorityQueue<int[], long> queue = new(items); | ||
|
||
// T: O(k log(n)) | ||
for (int i = 0; i < k; i++) { | ||
result[i] = queue.Dequeue(); | ||
} | ||
return result.ToArray(); | ||
|
||
return result; | ||
} | ||
} |