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]; } };