Leetcode 215. Kth Largest Element in an Array

原題地址:https://leetcode.com/problems/kth-largest-element-in-an-array/description/

題目描述

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大的元素。

思路

用快速排序里的Partition部分來實(shí)現(xiàn)不斷縮小這個(gè)問題的規(guī)模直到找到目標(biāo)元素。
快速排序里的Partition函數(shù)會(huì)找到一個(gè)pivot元素,然后小于或等于這個(gè)pivot元素的值被放置在pivot的一側(cè),大于pivot元素的值被放在另一側(cè)。也即,pivot元素的下標(biāo)就能反映它的大小在整個(gè)數(shù)組里排第幾位。
應(yīng)用到本題里,將比pivot元素大的數(shù)都放在pivot的左側(cè),pivot的下標(biāo)加上1就是pivot元素大小的排名(題目要找第k個(gè)元素,k從1開始,而下標(biāo)從0開始)。再根據(jù)kpivot下標(biāo)的大小情況來決定是直接返回當(dāng)前的pivot,或是在pivot元素的左側(cè)右側(cè)進(jìn)行遞歸處理。

代碼

class Solution {
public:
    
    int Partition(vector<int>& nums,int start,int end){
        if(start==end){
            return start;
        }
        int pivot_value = nums[start];
        int split=start+1;
        for(int i=start+1;i<=end;i++){
            if(nums[i]>pivot_value){
                int temp = nums[i];
                nums[i] = nums[split];
                nums[split]=temp;
                split++;
            }else{
            //pass
            }
        }
        int temp =nums[start];
        nums[start] = nums[split-1];
        nums[split-1]=temp;
        return split-1;
    }
    
    int  RealFind(vector<int>& nums,int k,int start,int end ){
        int pivot = Partition(nums,start,end);
        if(pivot==k){
            return nums[pivot];
        }else if(pivot>k){
            return RealFind(nums,k,start,pivot-1);
        }else{
            return RealFind(nums,k,pivot+1,end);
        }
    }
    
    int findKthLargest(vector<int>& nums, int k) {
        return RealFind(nums,k-1,0,nums.size()-1);
    }
};

這里貼一段自己以前學(xué)習(xí)的時(shí)候記錄的對(duì)于這種解法的更詳細(xì)的筆記

TIM截圖20170913091111.png

《算法導(dǎo)論》第9章更詳細(xì)地討論了這個(gè)問題,還介紹了一種最壞情況下運(yùn)行時(shí)間為O(n)的算法,有空再補(bǔ)充。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,923評(píng)論 0 33
  • 按照最理想的狀態(tài)應(yīng)該是每天都在學(xué)習(xí)中度過,這樣才算美好的一天,但是沒辦法,因?yàn)榻裉彀峒?。想起自己搬家的歷程,在北京...
    WanLum閱讀 338評(píng)論 0 1
  • 我等你開等你遲遲的來,捎上那邊的雪和濕潤的衣衫小爐尚未溫?zé)?,也未有一朵野云來敲窗。草塘睡著了,已安放不下一片很薄?..
    _柚子_閱讀 476評(píng)論 0 7
  • 好?。?/div>
    德菲閱讀 277評(píng)論 0 0
  • “有一種餓叫媽媽覺得我餓?!庇绕涫菍殞毶狭擞變簣@后,一天有兩頓是不和爸爸媽媽一起進(jìn)餐的。 “寶寶在幼兒園都吃了什么...
    了不起的爸媽閱讀 442評(píng)論 0 0

友情鏈接更多精彩內(nèi)容