开始更多借助STL的力量。
int majorityElement(vector<int>& nums) {
vector<int> elem;
vector<int> time; //elem存储元素值,time在elem相同下标位置处存储出现次数
for (auto iter = nums.begin(); iter != nums.end(); ++iter)
{
auto pos = find(elem.begin(), elem.end(), *iter);
if (pos == elem.end()) //iter指向一个新未记录在elem中的元素
{
elem.push_back(*iter);
time.push_back(1);
}
else//否则就直接在time相应元素位置处加一
{
int index = pos - elem.begin();
time[index]++;
}
}
int index = max_element(time.begin(), time.end()) - time.begin();
return elem[index];
}
发现这个居然还有一个好很多的算法——摩尔投票(Moore majority vote algorithm),但只能是有数字超过一半时候用。
perudocode
- Initialize an element m and a counter i with i = 0
- For each element x of the input sequence:
- if i = 0, then assign m = x and i = 1
- else if m = x, then assign i = i + 1
- else assign i = i − 1
- Return m
int majorityElement(vector<int>& nums) {
int m;
int count = 0;
for (int i = 0; i < nums.size(); i++) {
if (count == 0) {
m = nums[i];
count++;
} else if (nums[i] == m) {
count++;
} else
count--;
}
return m;
}