Lintcode 主元素

主元素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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值