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

【LeetCode】Majority Element

时间:2015-03-13 00:26:46      阅读:204      评论: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.


     思路:

     在数组中找出出现次数大于 n/2 的数。

     C++ 中map 对于这种统计次数的问题来说特别方便,而 Python 的话当然用字典。


     代码:

     C++

class Solution{
public:
    int majorityElement(vector<int> &num) {
        vector<int>::iterator it = num.begin();
        int n = num.size();
        map<int,int> count;
        for(;it != num.end();it++)
        {
            // 这里为什么不用判断键是否存在?因为不存在时初始化为 0
            if(++count[*it] > n/2)
            {
                return *it;
            }
        }
    }
};

     Python:

class Solution:
    # @param num, a list of integers
    # @return an integer
    def majorityElement(self, num):
        count = dict([])
        flag = len(num)/2
        for item in num:
            if item in count:
                count[item] = count[item] + 1
            else:
                count[item] = 1
                
            if count[item] > flag:
                return item

【LeetCode】Majority Element

标签:

原文地址:http://blog.csdn.net/jcjc918/article/details/43926577

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