1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| class Solution { public int kthSmallest(int[][] matrix, int k) { int n = matrix.length; int targetIndex = k - 1;
return quickSort(matrix, 0, n * n - 1, targetIndex); }
private int quickSort(int[][] matrix, int left, int right, int targetIndex) { int n = matrix.length; int pivotIndex = partition(matrix, left, right); if (pivotIndex < targetIndex) { return quickSort(matrix, pivotIndex + 1, right, targetIndex); } else if (pivotIndex > targetIndex) { return quickSort(matrix, left, pivotIndex - 1, targetIndex); } else { return matrix[pivotIndex / n][pivotIndex % n]; } }
private int partition(int[][] matrix, int left, int right) { int n = matrix.length; int pivotValue = matrix[left / n][left % n]; int i = left, j = right; while (i < j) { while (i < j && matrix[j / n][j % n] >= pivotValue) { j--; } while (i < j && matrix[i / n][i % n] <= pivotValue) { i++; }
swap(matrix, i, j); }
swap(matrix, i, left);
return i; }
private void swap(int[][] matrix, int i, int j) { int n = matrix.length;
int tmp = matrix[j / n][j % n]; matrix[j / n][j % n] = matrix[i / n][i % n]; matrix[i / n][i % n] = tmp; } }
|