Leetcode Kth largest Element in an Array (quick sort)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.