LeetCode 215-Kth Largest Element

2016-05-21  本文已影响88人  胡哈哈哈

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.

题意

找到一个无序数组中第k大的数。

分析

类似快速排序一样。每层递归中,对当前的nums区段内的元素进行操作:

AC代码

class Solution {
public:
    int answer;
    int findKthLargest(vector<int>& nums, int k) {
        find(nums, 0, nums.size() - 1, k);
        return answer;
    }

    void find(vector<int>& nums, int bottom, int top, int k) {
        int i = bottom, j = top, save = nums[bottom];
        while (i < j) {
            for (; i < j && nums[j] <= save; --j);
            nums[i] = nums[j];
            for (; i < j && nums[i] >= save; ++i);
            nums[j] = nums[i];
        }

        int rank = j - bottom + 1;
        if (rank == k) {
            answer = save; return;
        }
        if (rank > k) {
            find(nums, bottom, j - 1, k);
        } else {
            find(nums, j + 1, top, k - rank);
        }
    }
};
上一篇下一篇

猜你喜欢

热点阅读