码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Kth Largest Element in an Array

时间:2015-10-29 06:08:35      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/kth-largest-element-in-an-array/

采用quickSelect 算法,找第k大等于找第num.length + 1 - k小,这里k是从0开始所以就是 找num.length-k小。

findK就是找第k小函数,k从0开始。递归终止条件是 start>=end, 此时返回nums[start].

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

AC Java:

 1 public class Solution {
 2     public int findKthLargest(int[] nums, int k) {
 3         //QuickSelect
 4         return findK(nums, nums.length-k, 0, nums.length-1);
 5     }
 6     //findK 找第k小,k从0开始
 7     private int findK(int[] nums, int k, int start, int end){
 8         if(start >= end){
 9             return nums[start];
10         }
11         int m = partition(nums, start, end);
12         if(m == k){
13             return nums[m];
14         }else if(m < k){
15             return findK(nums, k, m+1, end);
16         }else{
17             return findK(nums, k, start, m-1);
18         }
19     }
20     
21     private int partition(int[] nums, int start, int end){
22         int pivot = nums[start];
23         int m = start;
24         int n = start + 1;
25         while(n<=end){
26             if(nums[n] < pivot){
27                 swap(nums, ++m, n);
28             }
29             n++;
30         }
31         swap(nums,start,m);
32         return m;
33     }
34     
35     private void swap(int[] nums, int i, int j){
36         int temp = nums[i];
37         nums[i] = nums[j];
38         nums[j] = temp;
39     }
40 }

 

LeetCode Kth Largest Element in an Array

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4919215.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!