215. K largest element in an array

Source: Internet
Author: User

Finds the largest element in an unordered array of the first K. Note that you need to look for the first K-largest element after the array is sorted, not the K-different element.

Example 1:

[3,2,1,5,6,4] 和K = 2 Output: 5

Example 2:

[3,2,3,1,2,4,5,5,6] 和k = 4 Output: 4

Description

You can assume that K is always valid and 1≤k≤ the length of the array.

The most brutal way is to sort all the data, then take out the number of K, but do a lot of unnecessary sorting;

Here with the quick sort, and the idea of two points to find the K-Big data;

With the first number pivot, find the position of the number in the ordered sequence, if the position of the number on the left of K, on the right of the number to continue to find, if the number on the right of K, on the left of the number to continue to find

1 classSolution {2  Public:3     intPartition (vector<int>& num,intLowintHigh ) {4         intPivot =Num[low];5          while(low<High ) {6              while(LowHigh ;7 swap (Num[low], Num[high]);8              while(LowLow ;9 swap (Num[low], Num[high]);Ten         } One         returnLow ; A     } -     intFindkthlargest (vector<int>& Nums,intk) { -         intL=0, R=nums.size ()-1; the         while(true){ -            intpos=partition (Nums, L, R); -            if(pos>k-1) r=pos-1; -            if(pos<k-1) l=pos+1; +            if(pos==k-1)returnnums[k-1]; -        } +     } A};

You can also use the heap sort to find, heap sort is not very familiar, and then do

215. K largest element in an array

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.