class Solution {
public int findKthLargest(int[] nums, int k) {
//利用快排的思路也可以解决
int k1=nums.length-k;
int low=0,high=nums.length-1;
while(low<high){
int j=partition(nums,low,high);
if(j==k1){
break;
}else if(j<k1){
low=j+1;
}else {
high=j-1;
}
}
return nums[k];
}
private static int partition(int [] a,int l,int h){
int i=l,j=h+1;
while(true){
while (a[++i] < a[l] && i < h) ;
while (a[--j] > a[l] && j > l) ;
if (i >= j) {
break;
}
swap(a,i,j);
}
swap(a,i,j);
return j;
}
private static void swap(int[] a, int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
leetcode215
最新推荐文章于 2025-05-29 21:59:44 发布