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

LeetCode169——Majority Element

时间:2015-01-15 13:02:28      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:算法   leetcode   c++   j strother moore   

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.

int majorityElement(vector &num) { }

题目大意

给定size 为n的数组,查找出主元素,就是出现次数大于n/2次的元素。你可以假定数组非空,而且主元素一定存在。

分析

首先肯定,这样的主元素只有一个,因为出现次数大于n/2。如何找到它呢?很暴力的做法是,两轮循环,然后把他找出来。时间复杂度是 O(n*n),这显然不是很好的方法。下面是我的一种解法:

int majorityElement(vector<int> &num) {
    std::map<int, int> im;
    for (int i = 0; i < num.size(); ++i){
        map<int, int>::iterator it = im.find(num[i]);
        if (it == im.end()) {
            im[num[i]] = 1;
        } else {
            im[num[i]]++;
        }
        if (im[num[i]] > num.size()/2) {
            return num[i];
        }
    }
    return 0;
}

这种解法还不是最好的,就这问题而已,有一种算法叫 Moore’s Voting Algorithm,由Robert S.Boyer 和J Strother Moore于1980年发明,是线性时间复杂度。

int majorityElement(vector<int> &num) {
    int majority;
    int cnt = 0;
    for(int i=0; i<num.size(); i++){
        if ( cnt ==0 ){
            majority = num[i];
            cnt++;
        }else{
            majority == num[i] ? cnt++ : cnt --;
            if (cnt >= num.size()/2+1) return majority;
        }
    }
    return majority;
}

当然,这种算法对于存在主元素的数组是有效的,如:

A A A C C B B C C C B C C

它肯定能返回主元素C。但是,如果不存在主元素,那么得到的结果就跟遍历顺序有关了。如:

A A A C C C B

如果是从左到右,那么结果是B,如果是从右到左,那么结果是A。

以上。

LeetCode169——Majority Element

标签:算法   leetcode   c++   j strother moore   

原文地址:http://blog.csdn.net/booirror/article/details/42738563

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