问题描述
小R从班级中抽取了一些同学,每位同学都会给出一个数字。已知在这些数字中,某个数字的出现次数超过了数字总数的一半。现在需要你帮助小R找到这个数字。
测试样例
样例1:
输入:
array = [1, 3, 8, 2, 3, 1, 3, 3, 3]
输出:3
样例2:
输入:
array = [5, 5, 5, 1, 2, 5, 5]
输出:5
样例3:
输入:
array = [9, 9, 9, 9, 8, 9, 8, 8]
输出:9
思路
双重循环计数即可,这里我们使用algorithm头文件+count(array.begin(),array.end(),array[i])来实现计数
代码实现
#include <iostream>
#include<algorithm>
#include <vector>
using namespace std;
int solution(vector<int> array) {
// Edit your code here
for(int i=0;i<array.size();i++){
int sum =count(array.begin(),array.end(),array[i]);
if(sum>(array.size()/2))
return array[i];
}
return 0;
}
int main() {
// Add your test cases here
cout << (solution({1, 3, 8, 2, 3, 1, 3, 3, 3}) == 3) << endl;
return 0;
}