链接: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; } };
原文地址:https://www.cnblogs.com/clown9804/p/12398286.html
时间: 2024-11-05 13:31:26