Kth Largest Element II Lintcode
Find K-th largest element in an array. and N is much larger than k.
Notice
You can swap elements in the array
Example
In array [9,3,2,4,8]
, the 3rd
largest element is 4
.
In array [1,2,3,4,5]
, the 1st
largest element is 5
, 2nd
largest element is 4
, 3rd
largest element is 3
and etc.
这道题可以用快速排序/快速选择的思想来做。
快排也写了不止一次了,但还是不够熟练。。。希望经过这次练习可以熟练一些。
需要注意的是注释的地方是不需要右边向左移动的,因为需要右边的指针停在第一个比pivot大的数的位置上,这样才可以调换。
class Solution { /** * @param nums an integer unsorted array * @param k an integer from 1 to n * @return the kth largest element */ public int kthLargestElement2(int[] nums, int k) { if (nums == null || nums.length == 0) { return -1; } if (nums.length == 1 && k == 1) { return nums[0]; } else if (nums.length == 1) { return -1; } int result = helper(nums, 0, nums.length - 1, nums.length - 1, k); return result; } private int helper(int[] nums, int left, int right, int pivot, int k) { int l = left, r = right; while (l < r) { while (l < r && nums[l] > nums[pivot]) { l++; } while (l < r && nums[r] <= nums[pivot]) { r--; } swap(nums, l, r); l++; // r--; } swap(nums, r, pivot); if (r == k - 1) { return nums[r]; } else if (r < k - 1) { return helper(nums, r + 1, right, pivot, k); } return helper(nums, left, r - 1, r - 1, k); } private void swap(int[] nums, int a, int b) { int tmp = nums[a]; nums[a] = nums[b]; nums[b] = tmp; } }
还可以用heap来做,可能相对慢一点?因为要全部排序?但这个思路要反应一下。。。到时候回顾回顾?
class Solution { /** * @param nums an integer unsorted array * @param k an integer from 1 to n * @return the kth largest element */ public int kthLargestElement2(int[] nums, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>(k); for (int i = 0; i < nums.length; i++) { pq.offer(nums[i]); if (pq.size() > k) { pq.poll(); } } return pq.peek(); } }