LeetCode OJ:Majority Element(主要元素)

时间:2021-09-16 22:19:51

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

求大于数组一半的元素,思想主要是对于大于数组一般的元素,给起计数起计数总和一定可以大于其他元素总和,代码如下:

 class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = ;
int res;
int sz = nums.size();
for(int i = ; i < sz; ++i){
if(count == ){
res = nums[i];
count++;
}else{
if(res == nums[i])
count++;
else
count--;
}
}
return res;
}
};