LeetCode 215. Kth Largest Element in an Array

原题链接在这里:https://leetcode.com/problems/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.

题解:

quickSelect 算法. 找第k大等于找,第num.length-k小.

findK就是找第k小函数, k从0开始.

递归终止条件是 start>=end, 或者start == end, 此时返回nums[start].

Time Complexity: O(n). Space O(1).

AC Java:

 1 class Solution {
 2     public int findKthLargest(int[] nums, int k) {
 3         if(nums == null || nums.length < k){
 4             return -1;
 5         }
 6         
 7         return findKth(nums, nums.length - k, 0 , nums.length - 1);
 8     }
 9     
10     private int findKth(int [] nums, int k, int l, int r){
11         if(l >= r){
12             return nums[l];
13         }
14         
15         int m = partition(nums, l, r);
16         if(m == k){
17             return nums[m];
18         }else if(m < k){
19             return findKth(nums, k, m + 1, r);
20         }else{
21             return findKth(nums, k, l, m - 1);
22         }
23     }
24     
25     private int partition(int [] nums, int l, int r){
26         int pivot = nums[l];
27         while(l < r){
28             while(l < r && nums[r] >= pivot){
29                 r--;
30             }
31             
32             nums[l] = nums[r];
33             
34             while(l < r && nums[l] <= pivot){
35                 l++;
36             }
37             
38             nums[r] = nums[l];
39         }
40         
41         nums[l] = pivot;
42         return l;
43     }
44     
45 }

类似Minimum Moves to Equal Array Elements II.

跟上Top K Frequent Elements.

posted @ 2015-10-29 01:07  Dylan_Java_NYC  阅读(480)  评论(0编辑  收藏  举报