215. 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.

一刷
Quick select
最好的情況下:
Discard half each time: n+(n/2)+(n/4)..1 = n + (n-1) = O(2n-1) = O(n), because n/2+n/4+n/8+..1=n-1.
原理是每次隨機(jī)取一個(gè)pivot, 然后把大于pivot的都放在右邊,小于pivot的都放在左邊。如果pivot就在k的位置,直接返回,否則縮小范圍繼續(xù)上面的步驟

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        if(nums == null || nums.length == 0) return Integer.MAX_VALUE;
        //nums.length - k, the start position of last k
        return find(nums, 0, nums.length-1, nums.length - k);
    }
    
    private int find(int[] nums, int start, int end, int k){
        if(start>end) return Integer.MAX_VALUE;
        int pivot = nums[end];
        int left = start;
        for(int i=start; i<end; i++){
            if(nums[i]<=pivot){
                swap(nums, left, i);
                left++;
            }
        }
        swap(nums, left, end);
        if(left == k) return nums[left];//found
        else if(left<k) return find(nums, left+1, end, k);
        else return find(nums, start, left-1, k);
    }
    
    private void swap(int[] nums, int left, int right){
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容