215. Kth Largest Element in an Array

Description

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.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Solution

MinHeap, O(n * logk), S(k)

class Solution {
    public int findKthLargest(int[] nums, int k) {
        Queue<Integer> queue = new PriorityQueue<>();
        
        for (int n : nums) {
            if (queue.size() < k) {
                queue.offer(n);
            } else if (n > queue.peek()) {
                queue.poll();
                queue.offer(n);
            }
        }
        
        return queue.peek();
    }
}

Quick-sort partition, time O(n), space O(1)

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

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

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