码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_num169_Majority Element

时间:2015-03-09 22:34:31      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:leetcode   algorithm   

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.

class Solution {
public:
    int majorityElement(vector<int> &num) {
        int max=num[0],count=1;
        for(int i=1;i<num.size();i++){
            if (count==0){
                max=num[i];
                count++;
            }
            else if (max==num[i]){
                count++;
            }
            else
                count--;
        }
        return max;
    }
};
利用Moore‘s voting algorithm选出次数超过半数以上的元素~~复杂度o(n)

leetcode_num169_Majority Element

标签:leetcode   algorithm   

原文地址:http://blog.csdn.net/eliza1130/article/details/44160173

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