Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input:[3,2,1,5,6,4]
and k = 2 Output: 5Example 2:
Input:[3,2,3,1,2,4,5,5,6]
and k = 4 Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
数组中的第K个最大的元素。
题目即是题意。这个题有几种不同的做法,但是考点应该是用快速排序 quick sort来解决问题。
暴力解。先用Java的内置函数对数组排序然后找出第K大的元素。
priority queue。用优先队列对数组排序,最后找出结果。
时间O(nlogk)
空间O(n)
Java实现
1 class Solution { 2 public int findKthLargest(int[] nums, int k) { 3 if (nums == null || nums.length == 0) { 4 return 0; 5 } 6 PriorityQueue<Integer> pq = new PriorityQueue<>(); 7 for (int num : nums) { 8 pq.offer(num); 9 if (pq.size() > k) { 10 pq.poll(); 11 } 12 } 13 return pq.peek(); 14 } 15 }
快速排序 quick sort。这里是试图将input数组由大到小排序。找一个数字当做pivot,比pivot大的摆在左边,比pivot小的摆在右边,最后将pivot放在他应该在的位置上(这也是快排的特点)。这样保证了pivot左侧的元素都比pivot大,而pivot右侧的元素都比pivot小。如果pivot的坐标正好是K则返回pivot的坐标;如果pivot比K大,则对pivot左侧所有的元素做快排;如果pivot比K小,则对pivot右侧所有的元素做快排。
时间O(nlogn), worse case O(n^2)
空间O(1)
Java实现
1 class Solution { 2 public int findKthLargest(int[] nums, int k) { 3 if (nums == null || nums.length == 0) { 4 return 0; 5 } 6 int left = 0; 7 int right = nums.length - 1; 8 while (true) { 9 int pos = partition(nums, left, right); 10 if (pos + 1 == k) { 11 return nums[pos]; 12 } else if (pos + 1 > k) { 13 right = pos - 1; 14 } else { 15 left = pos + 1; 16 } 17 } 18 } 19 20 private int partition(int[] nums, int left, int right) { 21 int pivot = nums[left]; 22 int l = left + 1; 23 int r = right; 24 while (l <= r) { 25 if (nums[l] < pivot && nums[r] > pivot) { 26 swap(nums, l++, r--); 27 } 28 if (nums[l] >= pivot) { 29 l++; 30 } 31 if (nums[r] <= pivot) { 32 r--; 33 } 34 } 35 swap(nums, left, r); 36 return r; 37 } 38 39 private void swap(int[] nums, int i, int j) { 40 int temp = nums[i]; 41 nums[i] = nums[j]; 42 nums[j] = temp; 43 } 44 }
相关题目
215. Kth Largest Element in an Array