Leetcode 0215: Kth Largest Element in an Array

题目描述:

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.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Example 3:

Input: s = “A”, numRows = 1
Output: “A”

Note:

You may assume k is always valid, 1 ≤ k ≤ array’s length.

Time complexity: O(n)
快速排序的思想:

  1. 在给定区间[start, end]中,选中某个数x,将大于等于x的放在左边,小于x的放在右边,其中[start, j]是大于等于x的区间,[j + 1,end]是小于x的区间
  2. 判断出第k大与j的大小关系,若符合大于等于x,则递归到[start, j]区间,否则递归到[j + 1,end]的区
class Solution {
    
    
    int[] nums;
    public int findKthLargest(int[] nums, int k) {
    
    
        this.nums = nums;
        return quick(0, nums.length-1, nums.length - k);
    }
    
    private int quick(int start, int end, int k){
    
    
        if(start >= end) return nums[end];
        int mid = start + (end - start)/2;
        int pivot = nums[mid];
        int l = start;
        int r = end;
        while(l <= r){
    
    
            while(l <= r && nums[l] < pivot){
    
    
                l++;
            }
            while(l <= r && nums[r] > pivot){
    
    
                r--;
            }
            if(l <= r){
    
    
                swap(l++, r--);
            }
        }
        
        if(l <= k){
    
    
            return quick(l, end, k);
        }
        if(k <= r){
    
    
            return quick(start, r, k);
        }
        return nums[k];
    }
    
    private void swap(int l, int r){
    
    
        int temp = nums[l];
        nums[l] = nums[r];
        nums[r] = temp;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113798956