Advertisement
exmkg

Untitled

Jan 12th, 2025
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.56 KB | None | 0 0
  1. class Solution {
  2.     public int[][] kClosest(int[][] points, int k) {
  3.         int n = points.length;
  4.  
  5.         int[][] dist_index = new int[n][2];
  6.         for (int i = 0; i < n; i++) {
  7.             dist_index[i][0] = points[i][0] * points[i][0] + points[i][1] * points[i][1];
  8.             dist_index[i][1] = i;
  9.         }
  10.  
  11.         quickSelect(dist_index, 0, n - 1, k - 1);
  12.  
  13.         int[][] answer = new int[k][2];
  14.         for (int i = 0; i < k; i++) {
  15.             answer[i] = points[dist_index[i][1]];
  16.         }
  17.         return answer;
  18.     }
  19.  
  20.     private static void quickSelect(int[][] arr, int left, int right, int k) {
  21.         // Take a random pivot from the whole range.
  22.         Random rand = new Random();
  23.         int randIndex = rand.nextInt(left, right + 1);
  24.         swap(arr, left, randIndex);
  25.  
  26.         int pivot = arr[left][0];
  27.         int storeIndex = left + 1;
  28.         for (int i = left + 1; i <= right; i++) {
  29.             if (arr[i][0] < pivot) {
  30.                 swap(arr, i, storeIndex);
  31.                 storeIndex++;
  32.             }
  33.         }
  34.         swap(arr, left, storeIndex - 1);
  35.         int l = storeIndex - 2;
  36.         int r = storeIndex;
  37.         while (l >= left && arr[l][0] == pivot) l--;
  38.         while (r <= right && arr[r][0] == pivot) r++;
  39.  
  40.         if (l + 1 <= k && k <= r - 1) return;
  41.         if (k <= l) quickSelect(arr, left, l, k);
  42.         else quickSelect(arr, r, right, k);
  43.     }
  44.  
  45.     private static void swap(int[][] arr, int i, int j) {
  46.         int[] tmp = arr[i];
  47.         arr[i] = arr[j];
  48.         arr[j] = tmp;
  49.     }
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement