Leetcode 215. Kth Largest Element in an Array 数组中第K大的数 in Java
215. Kth Largest Element in an Array
- Total Accepted: 76233
- Total Submissions: 213997
- Difficulty: Medium
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.
public class Solution { public int findKthLargest(int[] nums, int k) { return nums[partition(nums,0,nums.length-1,k)]; } public int partition(int[] nums,int left,int right,int k){ //类似quicksort if(left==right) return left; int standard = nums[left]; int m = left; //m代表比standard小的最后一个数的index int n = left+1; //n代表当前用于比较数的index while(n<=right){ if(nums[n]<standard) { swap(nums, ++m, n); //++m后代表就是大于standard的第一个数字的index,然后与n处的数交换,m又成为了比standard小的最后一个数的index } n++; } swap(nums,left, m);//最后把第一个standard和最后一个小于他的数交换,那个小的数到了第一,standard到了中间 //至此完成了以standard为标准的划分 int mid=m-left; //mid和lenTmp代表的是以left-right窃取的这段数组对应的值 int lenTmp=right-left+1;//m代表的是整个nums数组对应的值 if(lenTmp-mid==k) return m; //注意何处用mid和lenTmp,何处用m else if(lenTmp-mid<k) return partition(nums,left,m-1,k-(lenTmp-mid)); else return partition(nums,m+1,right,k); } public void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }