本文共 2373 字,大约阅读时间需要 7 分钟。
代码如下(Leetcode 215):
class Solution { public: int findKthLargest(vector & nums, int k) { priority_queue,greater > q; int i=0; for(;i q.top()){ q.pop(); q.push(nums[i]); } return q.top(); }};
运行结果:
2. 思路2:基于快排思想(partition)
- partition过程(升序):
- 找当前arr最左边作为基准ref
- 循环条件:left < right
- 右➡️左:找到比ref小的,放在左边
- 左➡️右:找到比ref大的,放在右边
- 当left == right时结束循环,这个坐标就是ref应该在的index
int partition(vector & arr,int l,int r){ int ref = arr[l]; while(l=ref) r--; arr[l]=arr[r]; while(l
回到此题:
- 对最左数作为基准ref进行partition,得到该ref应在的index
- left < right 时进行循环:
- 若index < K-1 : 说明第 K 大在右边,left = index + 1,继续partition
- 若index > K-1:说明第 K 大在左边,right = index -1,继续partition
- left == right 时第K个数即为第K大
代码如下(牛客NC88):
class Finder { public: int findKth(vector a, int n, int K) { int left=0,right=n-1; while(left
3. 思路3:自己实现堆调整
代码如下:
class Solution { public: int findKthLargest(vector & nums, int k) { //首先进行堆调整,把前k个建为小根堆 for(int i=k/2-1;i>=0;i--) heapAdjust(nums,i,k-1); //对后面的n-k个数,如果比堆顶大就交换,然后再进行堆调整 for(int j=k;jnums[0]){ swap(nums[0],nums[j]); heapAdjust(nums,0,k-1); } } return nums[0]; } //小根堆的调整 void heapAdjust(vector & nums,int start,int end){ int dad=start; int son=2*dad+1; while(son<=end){ if(son+1<=end && nums[son+1]
转载地址:http://abzcz.baihongyu.com/