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

LeetCode Kth Largest Element in an Array

时间:2015-05-25 00:53:14      阅读:178      评论: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.

都第几次多这样的题了,还是bug多得飞起

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int len = nums.size();
        
        int start = 0;
        int end = len;
        // convert to kth smallest element sematic
        k = len - k + 1;
        while (start < end) {
            int idx = partition(nums, start, end);

            if (idx == k - 1) {
                return nums[idx];
            } else if (idx < k - 1) {
                start = idx + 1;
                k = k - (idx - start + 1);
            } else {
                end = idx;
            }
        }
        return nums[start];
    }
    
    int partition(vector<int>& nums, int start, int end) {
        if (start >= end) {
            return -1;
        }
        int pv = nums[--end];
        int div = start;
        for (int i=start; i<end; i++) {
            if (nums[i] < pv) {
                swap(nums[i], nums[div]);
                div++;
            }
        }
        swap(nums[div], nums[end]);
        return div;
    }
};

 

LeetCode Kth Largest Element in an Array

标签:

原文地址:http://www.cnblogs.com/lailailai/p/4526872.html

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