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
| class Solution { private static final Random rand = new Random();
public int findKthLargest(int[] nums, int k) { return partition(nums, 0, nums.length-1, k); }
private int partition(int[] nums, int left, int right, int k) { swap(nums, left, left+rand.nextInt(right - left + 1)); int pivot = nums[left], i = left+1, j = right; while (true) { while (i <= j && nums[i] > pivot) i++; while (i <= j && nums[j] < pivot) j--; if (i >= j) break; swap(nums, i, j); i++; j--; } swap(nums, left, j); if (j == k-1) return nums[k-1]; else if (j < k) return partition(nums, j+1, right, k); else return partition(nums, left, j-1, k); }
private void swap(int[] nums, int l, int r) { int tmp = nums[l]; nums[l] = nums[r]; nums[r] = tmp; }
public static void main(String[] args) { Solution s = new Solution(); int[] nums= new int[]{4,5,6,7,0,1,2}; int k = 0; System.out.println(s.findKthLargest(nums, k)); } }
|