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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容