剑指offer题目28:数组中出现次数超过一半的数字
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
解答思路
第一个想法还是想桶排序一样,直接遍历统计每个数字出现的次数。。
最优解
由于数组当中肯定有比数组长度超过1半的数,所以我们可以如下去做,记录第1个数以及次数times设置为1,如果下一个数不是和记录的数不相同,则times-1,否则times+1,如果times等于0,则把下一个数换成当前记录的数,且times重置为1。
但是还要考虑边界情况,就是如果不存在的情况,所以我们在获得结果之后还是要遍历一次原数组的,统计一下出现的次数。。
实现代码
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
if(numbers.empty()) {
return 0;
}
int times = 1; // 记录出现次数
int current = numbers[0]; // 记录当前第一个元素
for (int i = 1; i < numbers.size(); ++i)
{
if(numbers[i] == current) {
++times;
} else if(--times == 0) {
current = numbers[i];
times = 1;
}
}
if(checkIsValid(&numbers, current)) {
return current;
} else {
return 0;
}
}
bool checkIsValid(vector<int>* numbers, int number) {
int times = 0;
int size = (*numbers).size();
for (int i = 0; i < size; ++i)
{
if((*numbers)[i] == number) {
++times;
}
}
if(times * 2 > size) {
return true;
}
return false;
}
};
作者:大傻逼
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号