#215. Kth Largest Element in an Array

Posted 东方春

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#215. Kth Largest Element in an Array相关的知识,希望对你有一定的参考价值。

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        return findInner(nums, 0, nums.size()-1,k);
    }
    
    
    int findInner(vector<int>& nums, int iLeft,int iRight,int k){
        if(iRight == iLeft)  return nums[iLeft];
        int idx = rand()%(iRight - iLeft + 1) + iLeft;
        int pivot = nums[idx];
        nums[idx] = nums[iLeft];
        int iBegin = iLeft;
        int iEnd = iRight;
        
        while (iBegin < iEnd) {
               while (iBegin < iEnd && nums[iEnd] <= pivot) {
                     iEnd--;
               }
               nums[iBegin] = nums[iEnd];
               while (iBegin < iEnd && nums[iBegin] >= pivot) {
                     iBegin++;
               }
               nums[iEnd] = nums[iBegin];
        }
        nums[iBegin] = pivot; //iBegin == iEnd

        //divide and  conquer
        int iLeftPartNum = iBegin - iLeft;
        if(iLeftPartNum == k - 1)
               return nums[iBegin];
        else if(iLeftPartNum > k - 1){
              return findInner( nums, iLeft,iBegin-1, k);
        }
        else if(iLeftPartNum < k - 1){
              return findInner( nums,iBegin+1, iRight, k-(iLeftPartNum+1));
        }
        
        
        
    }
};

  

以上是关于#215. Kth Largest Element in an Array的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-215. Kth Largest Element in an Array

#Leetcode# 215. Kth Largest Element in an Array

LeetCode OJ 215. Kth Largest Element in an Array 堆排序求解

LN : leetcode 215 Kth Largest Element in an Array

215. Kth Largest Element in an Array

215. Kth Largest Element in an Array