题解 | #数组中出现次数超过一半的数字#
数组中出现次数超过一半的数字
https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
抵消法:
class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { if(numbers.empty())return 0; int result=numbers[0]; int times=1; for(int i=1;i<numbers.size();i++){ if(times!=0){ if(result==numbers[i]){ ++times; }else{ --times; } }else{ result=numbers[i]; times=1; } } int count=0; for(int i=0;i<numbers.size();i++){ if(result==numbers[i]){ ++count; } } if(count>numbers.size()/2){ return result; }else{ return 0; } } };