LeetCode 169. Majority Element

169. Majority Element

Description

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.

Solution

  • 题意即寻找在给定数组中出现次数超过半数的数字,题目保证这样的数字存在。
  • 我的解法是先排序,那么中间那个数必定是我们要的数,因为我们要的数对的个数是超过半数的,无论它从哪里开始,总能够覆盖中间的下标,代码如下
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        return nums[nums.size() / 2];
    }
};
  • 在翻看题解的过程中,发现了一种很高效的算法——Boyer-Moore Majority Vote Algorithm,能够在O(N)的时间和O(1)的空间内找到超过半数的数字,实现很简单,但是我还是没能理解这样做的道理,如果有好的理解方式,请不吝指教。
  • 摩尔投票算法的描述就是:算法在局部变量中定义一个序列元素(m)和一个计数器(i),初始化的情况下计数器为0. 算法依次扫描序列中的元素,当处理元素x的时候,如果计数器为0,那么将x赋值给m,然后将计数器(i)设置为1,如果计数器不为0,那么将序列元素m和x比较,如果相等,那么计数器加1,如果不等,那么计数器减1。处理之后,最后存储的序列元素(m),就是这个序列中最多的元素。
  • 代码如下
class Solution {
public:
    int majorityElement(vector<int>& nums)
    {
        int cand;
        int count = 0;
        for(int i = 0; i<nums.size();i++)
        {
            if(i == 0 ||count == 0)
            {
                cand = nums[i];
                count = 1;
            }
            else if(nums[i] == cand)
                count++;
            else
                count--;
        }
        return cand;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值