Problem:
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的,有一点我们需要清楚,就是这样的元素在一个数组里面只能存在一个,明白这个问题,我们就好解决问题了
因为是需要考虑数字出现的次数,我们可以使用C++ STL中的关联容器map来解决,就是统计每个数字出现的次数,当出现一个map的value大于n/2返回key就行了。
int majorityElement(vector<int>& nums) {
map<int, int> counts;
int n = nums.size();
for (int i = 0; i < n; i++)
if (++counts[nums[i]] > n / 2)
return nums[i];
}