选众数
定义测试变量 test,假定它是众数
定义变量 count,统计出现次数。
1/ 假定首元素为众数,出现一次,次数+1;
2/ 判断后续元素与众数的异同,若相同,次数+1;若相异,次数-1;
3/ 当次数为0时,重新确定众数,直到数组尾部。
4/ 遍历数组,统计选定众数出行的次数;
5/ 次数大于一半,返回该数。
6/ 否则,返回0;
class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { int len=numbers.size(); // 找潜在的大于数组一半长度的众数 // 假定为初始元素 int test=0; int count=0; //计数器 for(int i=0;i<len;i++){ if(count==0){ test=numbers[i]; count++; } else { if (test==numbers[i]) count++; else count--; } } count=0;//清零 //检验数组众数与选出的潜在对象是否相等 for(const int k:numbers){ //vecotr 遍历数组 if(k==test)count++; } if(count>numbers.size()/2) return test; return 0; } };