[LeetCode 169]Majority Element: Moore Voting Algorithm

问题来源

169.Majority Element
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.**
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question

问题链接

问题简述

在一维数组中找到多数元素:在数组中出现次数一半( ⌊ n/2 ⌋)以上假设多数元素总是存在。

算法来源

A Linear Time Majority Vote Algorithm

算法原文

Majority Vote Algorithm:
We will sweep down the sequence starting at the pointer position shown above.
As we sweep we maintain a pair consisting of a current candidate and a counter. Initially, the current candidate is unknown and the counter is 0.
When we move the pointer forward over an element e:
If the counter is 0, we set the current candidate to e and we set the counter to 1.
If the counter is not 0, we increment or decrement the counter according to whether e is the current candidate.
When we are done, the current candidate is the majority element, if there is a majority.

算法简述

在数组中删除每对不同元素,最后得到的便是多数元素。

代码示例

/*keep iterate the array and find pairs of numbers that are different.*/
    int majorityElement(vector<int>& nums) 
    {
        int candidate=0;//keep first of the pair.
        int count=0;//the number of pairs to be found. 
        for(int i=0;i!=nums.size();i++)
        {
            if(count==0)
            {
                candidate=nums[i];
                count=1;
            }
            else
            {
                if(candidate==nums[i])//have to find more than one pair.
                count++;
                else//If found , "delete" the pair(s).
                count--;
            }
        }
        return candidate;
    }

复杂度分析

时间复杂度O(n) 空间复杂度O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值