LeetCode 215-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.

題意

找到一個無序數(shù)組中第k大的數(shù)。

分析

類似快速排序一樣。每層遞歸中,對當(dāng)前的nums區(qū)段內(nèi)的元素進(jìn)行操作:

  • 保存當(dāng)前區(qū)段的第一個元素nums[bottom]save
  • 類似快排,將大于save的元素移到左側(cè),小于save的移到右側(cè)
  • 通過下標(biāo)相減得知save在當(dāng)前區(qū)段中的次序rank
  • rank == k,則save就是第k大的數(shù)。
  • rank < k,則第k大的數(shù)在save所在位置的右側(cè),進(jìn)入下一層遞歸。
  • rank > k,則第k大的數(shù)在save所在位置的左側(cè),進(jìn)入下一層遞歸。

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);
        }
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容