数组中有一个数字出现的次数超过数组长度的一半,笔记
class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { float len=numbers.size(); if(len==0) return 0; if(len==1) return numbers[0]; float half=len/2; int count=1; for(int i=0;i<len-1;i++,count=1) { for(int j=i+1;j<len;j++) { if(numbers[i]==numbers[j]) count ++; if(count>half) return numbers[i]; } } return 0; } };
调试错误分析:
1.未考虑出现一个数字的情况
2.count,计数要及本次的数据,所以要赋值未1,
3.count在外循环里面要重新计数赋值