Skip to content

Commit

Permalink
Update 215.Kth-Largest-Element-in-an-Array.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Jun 29, 2020
1 parent ab81661 commit 7e27d10
Showing 1 changed file with 16 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,23 @@ class Solution {
public:
int findKthLargest(vector<int>& nums, int k)
{
return QuickSort(nums,nums.size()+1-k);
}

int QuickSort(vector<int>&nums, int n)
{
int pivot=nums[nums.size()/2];

int count = 0;
vector<int>small;
vector<int>large;

for (int k=0; k<nums.size(); k++)
long left = INT_MIN, right = INT_MAX;
while (left<right)
{
if (nums[k]==pivot)
count++;
else if (nums[k]>pivot)
large.push_back(nums[k]);
int mid = right-(right-left)/2;
if (count(nums,mid) >=k)
left = mid;
else
small.push_back(nums[k]);
}

if (n<=small.size())
return QuickSort(small,n);
else if (n>small.size()+count)
return QuickSort(large,n-small.size()-count);
else
return pivot;
right = mid-1;
}
return left;
}

int count(vector<int>&nums, int t)
{
int ret = 0;
for (auto x: nums)
ret += (x>=t);
return ret;
}
};

0 comments on commit 7e27d10

Please sign in to comment.