zoukankan      html  css  js  c++  java
  • #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));
            }
            
            
            
        }
    };
    

      

  • 相关阅读:
    JS高级
    函数作用域面试题
    11.14
    11.13
    Redux知识
    react-router-dom
    react 的三大属性
    vuex
    数组的扩展
    函数作用域和 class
  • 原文地址:https://www.cnblogs.com/dongfangchun/p/7767950.html
Copyright © 2011-2022 走看看