leetcode Majority Element

来源:互联网 发布:java反射得到属性 编辑:程序博客网 时间:2024/06/13 18:03

原题链接:https://leetcode.com/problems/majority-element/

Description

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 {    typedef unordered_map<int, int> UMAP;public:    int majorityElement(vector<int>& nums) {        UMAP mp;        int ans = 0, n = (int)nums.size();        for (auto &r : nums) { mp[r]++; }        for (auto &r : mp) {            if (r.second > n / 2) {                ans = r.first;             }        }        return ans;    }};
0 0