剑指OFFER----面试题39. 数组中出现次数超过一半的数字
链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/
思路:
cnt记录个数,val记录值;遍历数组,若等于val,则cnt++,否则cnt--,若cnt为0,则重置,最后val即为结果。
代码:
class Solution { public: int majorityElement(vector<int>& nums) { int cnt = 0, val = -1; for (auto x: nums) { if (!cnt) val = x, cnt = 1; else { if (x == val) cnt++; else cnt--; } } return val; } };