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.
- Difficulty: Easy
如果我们从数组中取出一对不相同的元素,
如果这两个元素都不是elem,那么取出它们两个之后,elem仍然会占据多一半。
如果这两个元素中有一个是elem,那么取出它们两个之后,elem还是会占据多一半。
因此,不管怎样,只要我们每次移除一对不同的元素,那么最后剩下的元素必然都是elem。
class Solution
{
public:
int majorityElement(vector<int> &nums)
{
int elem;
int times = 0;
for (auto x : nums)
{
if (times == 0)
{
elem = x;
times = 1;
}
else
{
times += (elem == x) ? 1 : -1;
}
}
if (times > 0)
{
return elem;
}
}
};