Leetcode[215]-kth largest Element in an Array

Source: Internet
Author: User

Find the kth largest element in an unsorted array. Note that it was the kth largest element in the sorted order and not the kth distinct element.

For example,
Given [3,2,1,5,6,4] k = 2 and, return 5 .

Note:
You may assume k are always valid, 1≤k≤array ' s length.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Method One: Sort O (nlogn) using STL

int findKthLargest(vector<int>int k) {    sort(nums.begin(),nums.end());    return nums[nums.size()-k];}

Law two: Write your own quick sort O (nlogn)

intFindkthlargest ( vector<int>& Nums,intk) {QuickSort (nums,0, Nums.size ());returnNums[nums.size ()-K];}voidQuickSort ( vector<int>&nums,intLeftintright) {inti = left, j = right-1;if(I < J) {intPO = nums[i]; while(I < J) { while(I < J && Nums[j] >= po) j--;if(I < J)            {nums[i++] = nums[j]; } while(I < J && Nums[i] <= po) i++;if(I < J)            {nums[j--] = nums[i];        }} Nums[i] = PO;        QuickSort (Nums, left, i); QuickSort (Nums, i+1, right); }}

Method Three: Using the construction method time complexity O (KLOGN)

int findKthLargest(vector<int>int k){    make_heap(nums.begin(), nums.end());    for(auto i=0; i<k-1;i++){        pop_heap(nums.begin(), nums.end());        nums.pop_back();    }    return nums.front();}

Method Four: This method is seen by the Forum, O (N)

intFindkthlargest ( vector<int>& Nums,intK) {intI, M, N, pivot, head =0, tail = nums.size ()-1, MAXV; while(1) {m = head, n= tail; Pivot = nums[m++]; while(M <= N) {if(Nums[m] >= pivot) m++;Else if(Nums[n] < pivot) n--;Else{Swap (nums[m++], nums[n--]); }        }if(M-head = = k)returnPivotElse if(M-head < k)             {k-= (m-head);          head = m; }Else{tail = m1; Head = head+1; }    }}

Leetcode[215]-kth 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.