LeetCode Devide & Conquer problem || 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.
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.
Difficulty:
medium

解題思路

如果不考慮題目tag,這道題非常簡單,直接用sort函數將序列排序,返回第K大的元素即可,easy.

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        int kmax = nums[nums.size() - k];
        return kmax;
    }
};

考慮題目Tag中Divide and Conquer的要求,則需要自己寫一個分治算法對序列進行排序了。排序算法中最經典的分治算法,就是快排(Quick Sort)了。
快排的基本思想是任取待排序對象序列中的某個對象(例如第一個對象)作爲樞軸(pivot),按照該對象的關鍵字大小,將整個對象劃分爲左右兩個子序列:

  • 左側子序列中所有對象的關鍵字都小於或等於樞軸對象的關鍵字;
  • 右側子序列中所有對象的關鍵字都大於樞軸對象的關鍵字;

樞軸對象則排在這兩個子序列中間(這也是該對象最終應安放的位置)。
然後分別對這兩個子序列重複實施上述方法,直到所有對象都排在相應的位置上爲止。

class Solution {
public:
    int partition(vector<int>& list, int low, int high){
        int pivot = list[low];
        while(low < high){
            while(low < high && list[high] >= pivot) high--;
            list[low] = list[high];
            while(low < high && list[low] <= pivot) low++;
            list[high] = list[low];
        }
        list[low] = pivot;
        return low;
    }
    void quickSort(vector<int> &list, int low, int high){
        if(low < high){
            int pivot = partition(list, low, high);
            quickSort(list, low, pivot - 1);
            quickSort(list, pivot + 1, high);
        }
    }
    int findKthLargest(vector<int>& nums, int k) {
        quickSort(nums, 0, nums.size() - 1);
        int kmax = nums[nums.size() - k];
        return kmax;
    }
};

然而題目還給了另一個提示Tag:Heap,先佔一個Tag,以後用堆排序完成排序後再來補充完整(●ˇ∀ˇ●)~

發佈了30 篇原創文章 · 獲贊 6 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章