算法設計課作業系列2——Kth Largest Element in an Array

算法設計課作業系列(2)

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.

解題過程

參考網址

白話經典算法系列之六 快速排序 快速搞定
注:以上的博客對於快速排序的解釋較爲容易理解,而這道題目的思想會借鑑到快排的思想,所以建議先學習並自行實現快排後再來解決這道題

思路分析

快排的思想大家都很熟悉,這道題也可以很簡單地用快速排序去算出從大到小的序列然後求出第k個是多少,然而問題是我們有沒有必要去全部排序一遍?
我們注意到快速排序的每一輪都會有一個基準,而在排序之後,這個基準所在位置左邊都是比它小(大)的,而右邊都是更大(小)的。因此,我們在每次的排序結束後,只需要判斷基準所在的位置是在我們要的左邊還是右邊即可,之後再對半邊進行排序即可。
因此思路就是,同樣快排的步驟,不同的是,在每一輪排序完成後,若當前基準正好在k的位置,則返回,否則對左邊或右邊進行遞歸操作。

源代碼

#include<vector>
using namespace std;

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        return findKthLargest(nums.begin(), nums.size(), k);
    }
private:
    int findKthLargest(vector<int>::iterator nums, int size, int k) {
        if (size <= 1) {
            return nums[0];
        }
        int flag = nums[0];
        int front = 0;
        int back = size - 1;
        while (front < back) {
            while (front < back && nums[back] <= flag) {
                back--;
            }
            if (back <= front) {
                break;
            }
            nums[front++] = nums[back];
            while (front < back && nums[front] >= flag) {
                front++;
            }
            if (back <= front) {
                break;
            }
            nums[back--] = nums[front];
        }
        nums[front] = flag;
        if (front == k - 1) {
            return flag;
        } else if (front > k - 1) {
            return findKthLargest(nums, front, k);
        } else {
            return findKthLargest(nums + front + 1, size - front - 1, k - front - 1);
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章