leetcode解题报告(21):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.

分析

unordered_map来做,以元素值为key,元素个数为value。然后遍历这个map,判断有没有元素个数大于 ⌊ n/2 ⌋,如果有,就返回这个元素,否则继续遍历,直到遍历结束。

代码如下:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        unordered_map<int,int>m;
        for(int num : nums)
            ++m[num];
        for(auto it = m.begin(); it != m.end(); ++it){
            if(it->second > nums.size() / 2)return it->first;
        }
        return 0;
    }
};
posted @ 2017-05-16 18:14  larryking  阅读(114)  评论(0编辑  收藏  举报