快速排序模板
class Solution {
int[] nums;
void qselect(int l, int r) {
if(l >= r) return;
int x = nums[l];
int i = l -1, j = r + 1;
while(i < j) {
do i++; while(nums[i] < x);
do j--; while(nums[j] > x);
if(i < j) swap(i, j);
}
qselect(l, j);
qselect(j + 1, r);
}
void swap(int i, int j) {
int x = nums[i];
nums[i] = nums[j];
nums[j] = x;
}
寻找第K大元素
class Solution {
Random random=new Random();
public int findKthLargest(int[] nums, int k) {
return quickSelect(nums,k,0,nums.length-1);
}
public int quickSelect(int[] nums,int k,int left,int right){
int index=random.nextInt(right-left+1)+left;
int target=nums[index];
nums[index]=nums[left];
int i=left,j=right;
while(i<j){
while(i<j&&nums[j]<=target) j--;
nums[i]=nums[j];
while(i<j&&nums[i]>=target) i++;
nums[j]=nums[i];
}
nums[i]=target;
if(i==k-1) return nums[i];
else if(i>k-1) return quickSelect(nums,k,left,i-1);
else return quickSelect(nums,k,i+1,right);
}
}