面试题29—数组中出现次数超过一半的数字

来源:互联网 发布:中国科学院大学知乎 编辑:程序博客网 时间:2024/06/07 20:10
题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

代码示例:

#include<iostream>using namespace std;bool MoreThanHalf(int a[], int n, int &res){if (a == NULL || n <= 0)return false;int times = 1;res = a[0];for (int i = 1; i < n; i++){if (times == 0){res = a[i];times++;}else{if (a[i] == res)times++;else{times--;}}}//int count = 0;for (int i = 0; i < n; i++){if (a[i] == res)count++;}if (count * 2 > n)return true;elsereturn false;}int main(){const int n = 9;int a[n] = { 5,0,4,5,6,5,5,8,5};int res = 0;bool flag = MoreThanHalf(a, n, res);if (flag){cout << "超过一半的数字是:" << res << endl;}else{cout << "该数组中没有超过一半的数字!" << endl;}}


阅读全文
0 0
原创粉丝点击