leetcode解题报告(31):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.

分析

代码如下:

class Solution {
public:
    int partition(vector<int>&nums,int p,int r)
    {
        int x = nums[r];
        int i = p - 1;
        for(int j = p; j != r; ++j)
            if(nums[j] < x)
                swap(nums[++i],nums[j]);
        swap(nums[i + 1],nums[r]);
        return i + 1;
    }
    int findKthLargest(vector<int>& nums, int k) {
        /*
        sort(nums.begin(),nums.end());
        return nums[nums.size() - k];
                                        */
        int p = 0,r = nums.size() - 1;
        while(true){
            int q = partition(nums,p,r);
            if(q < nums.size() - k)
                p = q + 1;
            else if(q > nums.size() - k)
                r = q - 1;
            else
                return nums[q];
        }
    }    
};
posted @ 2017-06-09 15:04  larryking  阅读(143)  评论(0编辑  收藏  举报