【leetcode】Majority Element

Question

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.

Code

#include<iostream>
#include<map>
#include<vector>
using namespace std;

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        map<int, int> count;
        int n = nums.size();
        for (int i = 0; i < n; i++) {
            count[nums[i]]++;
        }
        for (map<int, int>::iterator it = count.begin(); it != count.end(); it++) {
            if (it->second >= (n+1)/ 2) {
                return it->first;
            }
        }
        return -1;
    }
};

int main() {
    Solution so;
    vector<int> nums = {1,3,2,2};
    cout << so.majorityElement(nums) << endl;
    system("pause");
    return  0;
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_20976745/article/details/51556731
个人分类: Leetcode(easy)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭