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 1:
Input: [3,2,1,5,6,4]
and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6]
and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
題目大意:求一個未排序數組的第k大的數。
思路:
1、直接排序,時間複雜度:O(nlogn)
2、利用優先隊列,維持一個大小爲k的堆。時間複雜度:O(nlogk)
3、利用快排思想,時間複雜度:O(n)
C++代碼:
1 class Solution { 2 //劃分函數,返回的數的索引值對應最終排序後的位置 3 int partition(vector<int> &nums, int left, int right) { 4 int p = nums[left]; 5 while (left < right) { 6 while (left < right && nums[right] >= p) right--; 7 nums[left] = nums[right]; 8 while (left < right && nums[left] <= p) left++; 9 nums[right] = nums[left]; 10 } 11 nums[left] = p; 12 return left; 13 } 14 public: 15 int findKthLargest(vector<int>& nums, int k) { 16 int l = 0, r = nums.size() - 1; 17 while (l < r) { 18 int p = partition(nums, l, r); 19 if (p + k == nums.size()) { //滿足這個條件表明p指向的位置是第k大的數 20 return nums[p]; 21 } 22 if (p + k < nums.size()) //這個時候只需要排序p後半部分的數組即可找到最終的第k大數 23 l = p + 1; 24 else //此時只需要排序p前半部分 25 r = p - 1; 26 } 27 return nums[nums.size() - k]; 28 } 29 };