算法
时间复杂度:(O(n))
代码
class Solution {
public:
int majorityElement(vector<int>& nums) {
int ans = nums[0], count = 1;
for (int i = 1; i < nums.size(); ++i) {
if (count == 0) ans = nums[i];
if (nums[i] == ans) count += 1;
else count -= 1;
}
return ans;
}
};