题目描述:
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.
For example,
Given [3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
private int partition(int[] nums, int p, int r) { print(nums); int x = nums[r]; int i = p-1; for(int j=p;j<r;j++){ if(nums[j]<=x) { i++; swap(nums, i, j); } } swap(nums,i+1, r); return i+1; } private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } public void qSort(int[] a,int s,int t){ if(s<t){ int privotkey = partition(a, s, t); qSort(a, s, privotkey-1); qSort(a, privotkey+1, t); } } public void quickSort(int[] a){ qSort(a, 0, a.length-1); }这里的关键部分是partition过程,实现对nums[p...r]的原址排序,将小于nums[r]的排在左边,大于nums[r]的排在右边,返回nums[r]在数组中的应排的位置。
这个题借用此partition,代码如下:
public class Solution { public int findKthLargest(int[] nums, int k) { return findK(nums, nums.length-k, 0, nums.length-1); } private int findK(int[] nums, int k, int i, int j) { if(i>=j) return nums[i]; int m = partition(nums, i, j); if(m==k) return nums[m]; else if(m<k) { return findK(nums, k, m+1, j); } else { return findK(nums, k, i, m-1); } } private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } private int partition(int[] nums, int p, int r) { int x = nums[r]; int i = p-1; for(int j=p;j<r;j++){ if(nums[j]<=x) { i++; swap(nums, i, j); } } swap(nums,i+1, r); return i+1; } }