LeetCode 169. Majority Element

来源:互联网 发布:微信转换淘宝链接 编辑:程序博客网 时间:2024/06/05 04:15

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的数组,找出出现次数大于⌊ n/2 ⌋ 的元素。

思路:  

使用unordered_map<int,int> m来统计每个元素出现的次数,其中只有一个元素的出现次数会大于n/2,所以以元素出现次数大于n/2作为查找条件。

Code:

class Solution {public:    int majorityElement(vector<int>& nums) {        unordered_map<int,int> m;        int n = nums.size();        for(int i=0; i<n; i++){            if(++m[nums[i]]>n/2) return nums[i];        }     }};


原创粉丝点击