#leetcode#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.

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.


方法一: Arrays.sort( nums ), 则 nums[nums.length - k]就是 kth largest    O(nlogn)

方法二: 维护一个大小为 k 的 min heap, 所有元素从heap里走一遍, 则最后 heap.peek()就是 kth largest

方法三: quick select,注意 partition 的时候 左指针 <= pivot 都向右走, 扫描完一遍之后把 pivot 放到他的正确位置上,右指针位置为第一个小于比pivot大的值的位置, 即右指针位置是pivot的正确位置

时间复杂度  on average O(n), worst case O(n^2 )


// quick select

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        if(nums == null || nums.length == 0){
            return 0;
        }
        
        return findKthLargest(nums, k, 0, nums.length - 1);
    }
    
    private int findKthLargest(int[] nums, int k, int start, int end){
        int pivot = start;
        int left = start;
        int right = end;
        while(left < right){
            // after this while loop, nums[left] will be the first element from the left that is > pivot
            while(left < nums.length && nums[left] <= nums[pivot]){
                left++;
            }
            // after this while loop, nums[right] will be the first element from the right that is < pivot
            while(right >= 0 && nums[right] > nums[pivot]){
                right--;
            }
            if(left < right)
                swap(nums, left, right);
        }
        swap(nums, pivot, right); // move nums[pivot] to its correct position
        
        if(right == nums.length - k){
            return nums[right];
        }else if(right > nums.length - k){
            return findKthLargest(nums, k, start, right - 1);
        }else{
            return findKthLargest(nums, k, right + 1, end);
        }
    }
    
    
    
    private void swap(int[] A, int l, int r){
        int tmp = A[l];
        A[l] = A[r];
        A[r] = tmp;
    }
}


你可能感兴趣的:(LeetCode)