1. 程式人生 > >LeetCode 215. 數組中的第K個最大元素(Kth Largest Element in an Array)

LeetCode 215. 數組中的第K個最大元素(Kth Largest Element in an Array)

== size sta 有效 art 數組 end largest uic

題目描述

在未排序的數組中找到第 k 個最大的元素。請註意,你需要找的是數組排序後的第 k 個最大的元素,而不是第 k 個不同的元素。

示例 1:

輸入: [3,2,1,5,6,4] 和 k = 2
輸出: 5

示例 2:

輸入: [3,2,3,1,2,4,5,5,6] 和 k = 4
輸出: 4

說明:

你可以假設 k 總是有效的,且 1 ≤ k ≤ 數組的長度。

解題思路

利用快速排序的思想,在進行排序過程中每次可以確定一個元素的最終位置,若此位置為第K個最大元素,則直接返回此索引,否則繼續分治進行快速排序。

代碼

 1 class Solution {
 2 public
: 3 int findKthLargest(vector<int>& nums, int k) { 4 int idx = quickSort(nums, k, 0, nums.size() - 1); 5 return nums[idx]; 6 } 7 int quickSort(vector<int>& nums, int k, int start, int end){ 8 if(start < end){ 9 int p = partition(nums, start, end);
10 cout<<p<<endl; 11 if(p == k - 1) return p; 12 else{ 13 int idx = quickSort(nums, k, start, p - 1); 14 if(idx == k - 1) return idx; 15 else return quickSort(nums, k, p + 1, end); 16 } 17 }
18 else return start; 19 } 20 int partition(vector<int>& nums, int start, int end){ 21 int i = start - 1; 22 for(int j = start; j < end; j++) 23 if(nums[j] > nums[end]) 24 swap(nums[j], nums[++i]); 25 swap(nums[end], nums[++i]); 26 return i; 27 } 28 };

LeetCode 215. 數組中的第K個最大元素(Kth Largest Element in an Array)