春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现,某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。写出具体算法思路和代码实现,要求算法尽可能高效。
给定一个红包的金额数组gifts及它的大小n,请返回所求红包的金额。
测试样例:
[1,2,3,2,2],5
返回:2
/**
* 超过一半,如果存在,中位数就是.
* Created by ustc-lezg on 16/4/7.
*/
public class Solution {
public int getValue(int[] gifts, int n) {
return quickSort(gifts, 0, n - 1);
}
public int quickSort(int[] arr, int low, int high) {
int mid = (high + 1) >> 1;
int pivot = partition(arr, low, high);
while (pivot != mid) {//利用快排找到中位数
if (pivot < mid) {
pivot = partition(arr, pivot + 1, high);
} else {
pivot = partition(arr, low, pivot - 1);
}
}
int res = arr[pivot];
if (!check(arr, high + 1, res)) {
return 0;
}
return res;
}
public int partition(int arr[], int low, int high) {
int left = low;
int right = high;
int temp = arr[low];
while (left < right) {
while (left < right && arr[right] >= temp) {
--right;
}
if (left < right) {
arr[left] = arr[right];
}
while (left < right && arr[left] <= temp) {
++left;
}
if (left < right) {
arr[right] = arr[left];
}
}
arr[left] = temp;
return left;
}
public boolean check(int[] arr, int n, int res) {
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == res) {
++count;
}
}
if (count * 2 <= n) {
return false;
} else {
return true;
}
}
}