码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 169. Majority Element 多数投票算法(Boyer-Moore Majority Vote algorithm)

时间:2016-04-16 23:05:38      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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.

题解:运用多数投票算法的思路来解:从头到尾遍历数组,遇到两个不一样的数就把这两个数同时除去。除去的两个数可能都不是majority,也可能一个是majority一个不是,但是因为majority总数大于一半(注意不能等于一半),所以这么删完了最后肯定剩下的数是majority。(因为题目说了肯定有majority,如果没说,剩下的那个数未必是majority,还应该遍历一遍数组统计这个数的出现次数)。

这个算法的时间复杂度O(n),空间复杂度O(1)

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int cnt=0,ans=0;
        for(auto a:nums){
            if(cnt==0){
                ans=a;
                cnt=1;
            }
            else if(a==ans){
                cnt++;
            }
            else{
                cnt--;
            }
        }
        return ans;
    }
};

扩展:如果找改成大于[n/3]的,道理完全一样。参见这道题

leetcode 169. Majority Element 多数投票算法(Boyer-Moore Majority Vote algorithm)

标签:

原文地址:http://www.cnblogs.com/zywscq/p/5399567.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!