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

Leetcode: Kth Largest Element in an Array

时间:2015-12-17 08:13:48      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

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.

The same with Lintcode: Kth largest element

One thing to notice is 23-24 line, still find kth smallest element, do not need to decrease from k because the indexing(编号) does not change

 1 public class Solution {
 2     public int findKthLargest(int[] nums, int k) {
 3         int len = nums.length;
 4         return findKthSmallest(nums, 0, len-1, len-k+1);
 5     }
 6     
 7     public int findKthSmallest(int[] nums, int start, int end, int k) {
 8         int l = start;
 9         int r = end;
10         int pivot = end;
11         while (l < r) {
12             while (l<r && nums[l] < nums[pivot]) {
13                 l++;
14             }
15             while (l<r && nums[r] >= nums[pivot]) {
16                 r--;
17             }
18             if (l == r) break;
19             swap(nums, l, r);
20         }
21         swap(nums, l, pivot);
22         if (l+1 == k) return nums[l];
23         else if (l+1 < k) return findKthSmallest(nums, l+1, end, k);
24         else return findKthSmallest(nums, start, l-1, k);
25     }
26     
27     public void swap(int[] nums, int l, int r) {
28         int temp = nums[l];
29         nums[l] = nums[r];
30         nums[r] = temp;
31     }
32 }

 

Leetcode: Kth Largest Element in an Array

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5052893.html

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