关闭

【leetcode】Majority Element

57人阅读 评论(0) 收藏 举报
分类:

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;
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7285次
    • 积分:566
    • 等级:
    • 排名:千里之外
    • 原创:52篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条