problem:https://leetcode.com/problems/kth-largest-element-in-an-array/
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]
and k = 2, return 5.
Thought:
Quick Sort Partition
Code C + +:
classSolution { Public: intFindkthlargest (vector<int>& Nums,intk) {if(k <=0|| K >nums.size ()) { return 0; } intQ =partition (Nums); if(q +1==k) {returnNums[q]; } Vector<int>Left ; Vector<int>Right ; for(inti =0; i < Q; i++) {left.push_back (nums[i]); } for(inti = q +1; I < nums.size (); i++) {right.push_back (nums[i]); } if(q +1<k) {returnFindkthlargest (right, k-q-1); } Else { returnFindkthlargest (left, k); } } intPartition (vector<int>&nums) {Srand (unsigned (0))); intk = random ()%nums.size (); intKey =Nums[k]; inttemp =Nums[k]; NUMS[K]=Nums.back (); Nums.back ()=temp; intj =0; for(inti =0; I < nums.size ()-1; i++) { if(Nums[i] >key) { inttemp =Nums[i]; Nums[i]=Nums[j]; NUMS[J]=temp; J++; }} Temp=Nums.back (); Nums.back ()=Nums[j]; NUMS[J]=temp; returnJ; }};
Leetcode 215. Kth largest Element in an Array