Test instructions
What is the number of K-large in an unordered array?
Ideas:
According to the idea of the fast line, if each time divided into two paragraphs, set to L and R. If r>=k, the answer is set on the right, otherwise the left collection.
The 3-bit method is used here. Pay attention to the fast-line and write the dead loop.
1 classSolution {2 Public:3 intFindkthlargest (vector<int>& Nums,intk) {4 if(K>nums.size ())return 0;5 returnDFS (Nums,0, Nums.size ()-1, k);6 }7 8 intDFS (vector<int>& Nums,intSintEintk)9 {Ten intL=s, r=e; One //three-bit take-in method A if(nums[e]>Nums[s]) swap (nums[s],nums[e]); - if(nums[s]>nums[(s+e)/2]) Swap (nums[s],nums[(s+e)/2]); - the intMid=Nums[s]; - while(l<R) - { - while(L<r && Nums[r]>=mid) r--;//Find Small +nums[l]=Nums[r]; - while(L<r && Nums[l]<=mid) l++;//looking for big +nums[r]=Nums[l]; A } atnums[l]=mid; - intLen=e-l;//number of elements in the right part - if(len+1==K)returnmid; - if(len>=k)returnDFS (nums,l+1, e,k); - Else returnDFS (nums,s,l-1, k-len-1); - } in};AC Code
Quick line:
1 voidQuick (vector<int>& Nums,intSinte)2 {3 intL=s, r=e;4 //three-bit take-in method5 if(Nums[e]>nums[s]) swap (nums[s],nums[e]);//ask for Big6 if(nums[s]>nums[(s+e)/2]) Swap (nums[s],nums[(s+e)/2]);//in Demand7 intpivot=Nums[s];8 while(l<R)9 {Ten while(L<r && Nums[r]>=pivot) r--;//Find Small Onenums[l]=Nums[r]; A - while(L<r && Nums[l]<=pivot) l++;//looking for big -nums[r]=Nums[l]; the } -nums[l]=pivot; -Quick (nums,s,l-1); -Quick (nums,l+1, e); +}AC Code
Leetcode Kth largest Element in an Array (quick sort)