基于快速排序:
1 class Solution { 2 public: 3 /* 4 * param k : description of k 5 * param nums : description of array and index 0 ~ n-1 6 * return: description of return 7 */ 8 int kthLargestElement(int k, vector<int> nums) { 9 // write your code here 10 int left = 0, right = nums.size() - 1; 11 while (true) { 12 int pos = partition(nums, left, right); 13 if (pos == k - 1) return nums[pos]; 14 if (pos < k - 1) left = pos + 1; 15 if (pos > k - 1) right = pos - 1; 16 } 17 } 18 private: 19 int partition(vector<int>& nums, int left, int right) { 20 int pivot = nums[left]; 21 int l = left + 1, r = right; 22 while (l <= r) { 23 if (nums[l] < pivot && nums[r] > pivot) 24 swap(nums[l++], nums[r--]); 25 if (nums[l] >= pivot) l++; 26 if (nums[r] <= pivot) r--; 27 } 28 swap(nums[left], nums[r]); 29 return r; 30 } 31 };
时间: 2024-12-28 09:01:44