容易 主元素
40%
通过
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
Yes
样例
给出数组[1,1,1,1,2,2,2],返回 1
挑战
标签
Expand
要求时间复杂度为O(n),空间复杂度为O(1)
class Solution {
public:
/**
* @param nums: A list of integers
* @return: The majority number
*/
int majorityNumber(vector<int> nums) {
// write your code here
int len = nums.size();
int tag = 0;
int t = 0;
int cnt = 0;
for(int i = 0; i < len; i++){
if(0 == tag){
t = nums[i];
cnt = 1;
tag = 1;
}
else if(t == nums[i]) {
cnt++;
}
else {
cnt--;
if(0 == cnt)
tag = 0;
}
}
return t;
}
};