C++:主要元素

11 篇文章 1 订阅

C++:主要元素

问题描述

数组中占比超过一半的元素称之为主要元素。给你一个 整数 数组,找出其中的主要元素。若没有,返回 -1 。请设计时间复杂度为 O(N) 、空间复杂度为 O(1) 的解决方案。

 

示例 1:

输入:[1,2,5,9,5,9,5,5,5]
输出:5
示例 2:

输入:[3,2]
输出:-1
示例 3:

输入:[2,2,1,1,1,2,2]
输出:2

分析

  1. 最容易想到的一个方法是使用Hash表进行计数,依次遍历并判断当前数出现的次数是否大于长度的一半,该方法时间复杂度为O(n),空间复杂度为O(n)
  2. 注意到主元是超过一半的元素,因此可以考虑使用moor投票算法先找到出现最多的数,然后再统计其长度。

实现

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int Moore(vector<int> &nums);
int Hash(vector<int> &nums);
int main()
{
    vector<int> nums = {3,3,4};
    //return Hash(nums);
    return Moore(nums);
    system("pause");
} 

int Hash(vector<int>& nums)
{
    unordered_map<int,int> cnt;
    for(auto& num:nums)
    {
        if((++cnt[num]) > (nums.size()/2))
            return num;
    }
    return -1;
}

int Moore(vector<int>& nums)
{
    int major = -1, cnt = 0;
    for(auto& num:nums)
    {
        if(cnt == 0)
        {
            major = num;
            cnt = 1;
        }  
        else if(major == num)
            cnt++;
        else
            cnt--;
    }
    for(auto& num:nums)
    {
        if(major == num)
            cnt++;
    }
    if(cnt > nums.size()/2)
        return major;
    else
        return -1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值