排序LeetCode 215 Kth Largest Element in an Array

LeetCode 215

Kth Largest Element in an Array

  • Problem Description:
    返回數組的第k大元素,可採用快速排序的方法。快速排序每遍歷一次就確定一個元素在數組中的最終位置,比該元素大的位於該元素右側,比該元素小的位於該元素左側。通過每次遍歷後比較確定的位置和k 值大小,縮小區間範圍,最終即可求出第k大元素。
    具體的題目信息:
    https://leetcode.com/problems/kth-largest-element-in-an-array/description/
  • Example:
    這裏寫圖片描述
  • Solution:
class Solution {
public:
    int Partition(vector<int>& nums, int low, int high) {
        int pivot = nums[low];
        while(low<high) {
            while(low<high && nums[high]>= pivot) high--;
            nums[low] = nums[high];
            while(low<high && nums[low]<= pivot) low++;
            nums[high] = nums[low];
        }
        nums[low] = pivot;
        return low;
    }
    int findKthLargest(vector<int>& nums, int k) {
        if (nums.size() == 0) return 0;
        if (nums.size() == 1) return nums[0];
        k = nums.size()-k;
        int low = 0, high = nums.size()-1;
        while(low<high) {
            int pivot = Partition(nums, low, high);
            if (pivot == k) {
                break;
            } else if (pivot<k) {
                low = pivot+1;
            } else {
                high = pivot-1;
            }
        }
        return nums[k];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章