面试题五 数组中出现次数超过一半的数字 时间为O(n)

也就是说
该数字出现的次数比其他所有数字出现次数的和还要多。
因此可以保存两个值,一个数字,一个次数。

遍历时
1、如果数字相同,count++
2、如果count == 0 
      count = 1 number替换 
3、如果不相同 count--

int main(){
	int array[] = {3, 2, 3, 1, 3, 4};
	int number = array[0], count = 0;

	for (int i = 1; i < 6; i++){
		if (count == 0){
			count = 1;
			number = array[i];
		}
		if (array[i] != number){
			count--;
		}
		else{
			count++;
		}
	}
	cout << number << " " << count << endl;
	system("pause");
	return 0;
}

  

原文地址:https://www.cnblogs.com/MyGameAndYOU/p/4377548.html