主元素1
class Solution {
public:
/**
* @param nums: A list of integers
* @return: The majority number
*/
int majorityNumber(vector<int> nums) {
// write your code here
int n =1;
int temp=nums[0];
for(int i =0;i<nums.size();i++) {
if(nums[i]==temp)
n++;
else
n--;
if (n==0){
temp=nums[i];
n=1;
}
}
return temp;
}
};
主元素2
牛人代码
可表示为:若主元素个数-1,同时数组个数-k时,主元素不会被改变。
于是,可得出如下步骤:
1首先遍历数组,建立一个键为数组中元素,值为当前元素出现次数的hash表
2当hash表的大小小于k时,继续步骤1;否则继续步骤3
3对现在hash表中的所有键的值减1
4从hash表中剔除值为0的键值对
5持续进行以上步骤,直到所有数组元素全部被遍历完。
6对现在得到的这个hash表的值归0,
7遍历数组,统计现在hash表中的元素的个数,返回个数最多的那个元素,即主元素。
class Solution {
public:
/**
* @param nums: A list of integers
* @return: The majority number occurs more than 1/3.
*/
int majorityNumber(vector<int> nums) {
// write your code here
int size = nums.size(), hashMaxSize = 3, i = 0;
map<int, int> hashMap;//定义空的关联容器 hashMap,
map<int, int>::iterator it;//迭代器 类型变量
int result = 0, maxCount = 0;
for(i=0; i<size; i++) {
if(hashMap.size() < hashMaxSize) {
it = hashMap.find(nums[i]);//在hashMap中查找键num[i]所对应的值,不存在 返回末端的迭代器
if(it == hashMap.end()) {
hashMap.insert(pair<int, int>(nums[i], 1));
}
else {
(it->second)++;//first 指键值对中的键;second指键值对中的值
}
}
else {
for(it=hashMap.begin(); it!=hashMap.end(); it++) {
(it->second)--;
}
for(it=hashMap.begin(); it!=hashMap.end();) {
if(it->second == 0) {
hashMap.erase(it++);//删除键值为it++的元素
}
else {
it++;
}
}
}
}
for(it=hashMap.begin(); it!=hashMap.end(); it++) {
it->second = 0;
}
for(i=0; i<size; i++) {
it = hashMap.find(nums[i]);
if(it != hashMap.end()) {
it->second++;
if(maxCount < it->second) {
maxCount = it->second;
result = it->first;
}
}
}
return result;
}
};