**题目:**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
解题思路: 题目要寻找数组中出现次数超过 ⌊ n/2 ⌋ 次的元素,而且结果一定存在。那么可以选择一次的扫描整个数组,遇到不同的就把它们成对删除,还是相同的就把一个计数器加一,那么扫描完整个数组后,最后就能够得到所要的答案。
int majorityElement(vector<int>& nums)
{
int ans=0;
int count=0;
for(int i=0;i<nums.size();i++)
{
if(count==0)
{
ans=nums[i];
count++;
}
else
{
if(nums[i]==ans)
count++;
else
count--;
}
}
return ans;
}