0
点赞
收藏
分享

微信扫一扫

快排学习(LeetCode 215题)

给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5

示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
提示:
1 <= k <= nums.length <= 104
-104 <= nums[i] <= 104

class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> heap = new PriorityQueue<>();
        for(int num : nums){
            heap.offer(num);
            if(heap.size() > k){
                heap.poll();
            }
        }
        return heap.peek();
    }
}
class Solution {
    public int findKthLargest(int[] nums, int k) {
       int len = nums.length - 1;
       int target = len - k + 1;
       int start = 0,end = len;
       int index = partition(nums,start,end);
       while(index != target){
           if(index < target){
               start = index + 1;
           }else{
               end = index - 1;
           }
           index = partition(nums,start,end);
       }
       return nums[target];
    }
    public int partition(int[] nums,int start,int end){
        Random random = new Random();
        int pivot = random.nextInt(end - start + 1) + start;
        int first = start - 1;
        swap(nums,pivot,end);
        for(int i = start ; i < end; i++){
            if(nums[i] < nums[end]){
                first++;
                swap(nums,first,i);
            }
        }
        first++;
        swap(nums,end,first);
        return first;
    }
    public void swap(int[] nums,int i,int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
举报

相关推荐

0 条评论