给定一个数组,找到数组中出现次数超过n/2的主元素,此数组非空,且必定存在该主元素
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.
分析:
1,显然排序可以做,time o(nlg(n)),space o(1)
//思路首先:排序,返回中间位置的元素
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
return nums[nums.size()/2];
}
};
2,红黑树map来做,利用实值记录元素的出现次数,总是让当前的nums[i]在mapping中++,time o(n),space o(n)
//思路首先:
//红黑树map,总是让mapping[nums[i]]++
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int, int> mapping;
for (auto ite = nums.begin(); ite != nums.end();ite++)
if ( (++mapping[*ite]) > nums.size() / 2)
return *ite;
}
};
3.别人的算法:多数投票算法
如果counts==0,则将Majority的值设置为数组的当前元素,将count赋值为1;
反之,如果Majority和现在数组元素值相同,则counts++,反之counts-–;
重复上述两步,直到扫描完数组。
任何一个未超过一半次数的数,它的counts都不可能大于0,必将易主主元素值
任何一个出现超过一半次数的,它的counts都不可能降为0
class Solution {
public:
int majorityElement(vector<int>& nums) {
int Majority , counts = 0, n = nums.size();
for (int i = 0; i < n; i++) {
if (!counts) {//主元素Majority易主
Majority = nums[i];
counts = 1;
}
else
counts += (nums[i] == Majority ) ? 1 : -1;
}
return Majority;
}
};
学习和参考别人的总结:
http://blog.youkuaiyun.com/u012501459/article/details/46820823
/**********************************************来自九度的华丽分割线*****************************************************/
联动九度:
-
题目描述:
-
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。
-
输入:
-
每个测试案例包括2行:
第一行输入一个整数n(1<=n<=100000),表示数组中元素的个数。
第二行输入n个整数,表示数组中的每个元素,这n个整数的范围是[1,1000000000]。
-
输出:
-
对应每个测试案例,输出出现的次数超过数组长度的一半的数,如果没有输出-1。
-
样例输入:
-
91 2 3 2 2 2 5 4 2
-
样例输出:
-
2
排序取中间位置的元素,在检查一遍是否出现超过一半
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int n,m,i,j;
while(cin>>n&&n)
{
vector<int> vec;
for(i=0;i<n;++i)
{
cin>>m;
vec.push_back(m);
}
sort(vec.begin(),vec.end());
m=vec[n/2];
for(j=i=0;i<n;++i)
if(vec[i]==m)
++j;
if(j>n/2)
cout<<m<<endl;
else
cout<<"-1"<<endl;
}
return 0;
}
/**************************************************************
Problem: 1370
User: EbowTang
Language: C++
Result: Accepted
Time:100 ms
Memory:2296 kb
****************************************************************/
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.youkuaiyun.com/ebowtang/article/details/50542550
原作者博客:http://blog.youkuaiyun.com/ebowtang