题干
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的数组,让你找出里面的“主要元素”,“主要元素”是指在数组里面出现次数超过⌊ n/2 ⌋次的数。规定数组非空,且“主要元素”有且只有一个。
解题思路
如果你不会用C++的容器map, 可以直接暴力求解,对每个出现的元素都进行计数,最后找出符合要求的元素便可。
如果熟悉容器map,你会发现这道题用map来做超级合适,直接调用map代码会简洁很多。首先,声明一个类型为key类型为int, 第二个元素类型也为int的map容器,第一个用来表示元素,第二个int是此元素在数组中出现的次数。接下来要做的便是先遍历数组,对元素进行计数。再来就是遍历容器,找出次数超过⌊ n/2 ⌋的元素。
小优化:对于在前半个数组都没有出现过的元素,即使在后半个数组出现了,它的次数都不会超过⌊ n/2 ⌋,所以在计数时,对于在后半个数组新出现的元素,我们可以不用管它。
代码
class Solution {
public:
int majorityElement(vector<int>& nums) {
int size = nums.size();
map<int, int> count;
// 此容器第一个int是元素,第二个int是该元素出现的次数计数
for (int i = 0; i < nums.size(); i++) {
map<int, int>::iterator it;
it = count.find(nums[i]); // 找该元素是否出现过
if (it != count.end()) { // 如果该元素已经出现
it->second++; // 计数加一
} else {
if (i < nums.size() / 2 + 1)
count[nums[i]] = 1;
}
}
// 下面是遍历容器查询次数符合要求的元素
map<int, int>::iterator it;
it = count.begin();
while (it != count.end()) {
if (it->second > nums.size() / 2) {
return it->first;
}
it++;
}
}
};