使用快速排序找中位数,找到以后检查一下中位数是否出现了总次数的一半以上。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Gift {
public:
int getValue(vector<int> gifts, int n) {
if (n <= 0)
return -1;
int start = 0;
int end = n - 1;
int middle = (end - start) >> 1;//中位数的下标
int index;
index = partition(gifts, start, end);
while (index != middle) {
if (index > middle) { //index>middle,说明中位数在左边,我们需要左调整end
end = index - 1;
index = partition(gifts, start, end);
}
else { //index<middle,说明中位数在右边,需要右调整start
start = index + 1;
index = partition(gifts, start, end);
}
}
return check_more_than_half(gifts, n, gifts[middle]);
}
int partition(vector<int>&a, int low, int high)//选第一个元素为枢轴
{
while (low < high)
{
while (low < high && a[high] >= a[low]) high--;//此时枢轴的下标为low
swap(a[low], a[high]); //交换后枢轴的下标为high
while (low < high && a[low] <= a[high]) low++; //此时枢轴的下标为high
swap(a[low], a[high]);//交换后枢轴的下标为low
}
return low;//返回枢轴的下标
}
int check_more_than_half(vector<int>& gifts, const int n, int val) {
int cnt = 0;
for (auto i : gifts) {
if (i == val)
++cnt;
}
return (cnt != 0 && cnt > (n >> 1)) ? val : 0;
}
};
int main() {
Gift s;
vector<int>a = { 1,2,3,2,2 };
cout << s.getValue(a, 5) << endl;
system("pause");
return 0;
}
从大到小快速排序即可。
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int n = nums.size();
if (n <= 0)
return -1;
int start = 0;
int end = n - 1;
int index;
index = partition(nums, start, end);
while (index != k - 1) {
if (index > k - 1) { //index>k-1,说明要找的数在左边,我们需要左调整end
end = index - 1;
index = partition(nums, start, end);
}
else { //index<k-1,说明要找的数在右边,需要右调整start
start = index + 1;
index = partition(nums, start, end);
}
}
return nums[index];
}
int partition(vector<int>&a, int low, int high)//选第一个元素为枢轴
{
while (low < high)
{
while (low < high && a[high] <= a[low]) high--;//此时枢轴的下标为low
swap(a[low], a[high]); //交换后枢轴的下标为high
while (low < high && a[low] >= a[high]) low++; //此时枢轴的下标为high
swap(a[low], a[high]);//交换后枢轴的下标为low
}
return low;//返回枢轴的下标
}
};