[LeetCode] 215. Kth Largest Element in an Array

 

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

You must solve it in O(n) time complexity.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= k <= nums.length <= 105
  • -104 <= nums[i] <= 104

数组中的第K个最大的元素。

给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。

请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/kth-largest-element-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目即是题意。这个题有几种不同的做法,但是考点应该是用快速排序 quick sort 来解决问题。

暴力解。先用Java的内置函数对数组排序然后找出第K大的元素。

priority queue。用优先队列对数组排序,最后找出结果。

时间O(nlogk)

空间O(n)

Java实现

 1 class Solution {
 2     public int findKthLargest(int[] nums, int k) {
 3         if (nums == null || nums.length == 0) {
 4             return 0;
 5         }
 6         PriorityQueue<Integer> pq = new PriorityQueue<>();
 7         for (int num : nums) {
 8             pq.offer(num);
 9             if (pq.size() > k) {
10                 pq.poll();
11             }
12         }
13         return pq.peek();
14     }
15 }

 

快速排序 quick sort。这里是试图将 input 数组由大到小排序。找一个数字当做 pivot,比 pivot 大的摆在左边,比 pivot 小的摆在右边,最后将 pivot 放在他应该在的位置上(这也是快排的特点)。这样保证了 pivot 左侧的元素都比 pivot 大,而 pivot 右侧的元素都比 pivot 小。如果pivot的坐标正好是 K 则返回 pivot 的坐标;如果 pivot 的下标比 K 大,则对 pivot 左侧所有的元素做快排;如果 pivot 的下标比 K 小,则对 pivot 右侧所有的元素做快排。

时间O(nlogn), worse case O(n^2)

空间O(nlogn)

Java实现

 1 class Solution {
 2     public int findKthLargest(int[] nums, int k) {
 3         // corner case
 4         if (nums == null || nums.length == 0) {
 5             return Integer.MAX_VALUE;
 6         }
 7         return helper(nums, 0, nums.length - 1, nums.length - k);
 8     }
 9 
10     // quick select: kth smallest
11     private int helper(int[] nums, int start, int end, int k) {
12         if (start > end) {
13             return Integer.MAX_VALUE;
14         }
15         int pivot = nums[end];
16         int left = start;
17         for (int i = start; i < end; i++) {
18             if (nums[i] <= pivot) {
19                 swap(nums, left++, i);
20             }
21         }
22         swap(nums, left, end);
23 
24         if (left == k) {
25             return nums[left];
26         } else if (left < k) {
27             return helper(nums, left + 1, end, k);
28         } else {
29             return helper(nums, start, left - 1, k);
30         }
31     }
32 
33     private void swap(int[] nums, int i, int j) {
34         int temp = nums[i];
35         nums[i] = nums[j];
36         nums[j] = temp;
37     }
38 }

 

相关题目

215. Kth Largest Element in an Array

912. Sort an Array

973. K Closest Points to Origin

LeetCode 题目总结

posted @ 2020-06-12 06:59  CNoodle  阅读(153)  评论(0编辑  收藏  举报