We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 59a39a8 commit cc0526cCopy full SHA for cc0526c
solution/0900-0999/0973.K Closest Points to Origin/Solution3.java
@@ -0,0 +1,34 @@
1
+class Solution {
2
+ public int[][] kClosest(int[][] points, int k) {
3
+ int n = points.length;
4
+ int[] dist = new int[n];
5
+ int r = 0;
6
+ for (int i = 0; i < n; ++i) {
7
+ int x = points[i][0], y = points[i][1];
8
+ dist[i] = x * x + y * y;
9
+ r = Math.max(r, dist[i]);
10
+ }
11
+ int l = 0;
12
+ while (l < r) {
13
+ int mid = (l + r) >> 1;
14
+ int cnt = 0;
15
+ for (int d : dist) {
16
+ if (d <= mid) {
17
+ ++cnt;
18
19
20
+ if (cnt >= k) {
21
+ r = mid;
22
+ } else {
23
+ l = mid + 1;
24
25
26
+ int[][] ans = new int[k][0];
27
+ for (int i = 0, j = 0; i < n; ++i) {
28
+ if (dist[i] <= l) {
29
+ ans[j++] = points[i];
30
31
32
+ return ans;
33
34
+}
0 commit comments