【leetcode】Majority Element

来源:互联网 发布:airplayiphone连mac 编辑:程序博客网 时间:2024/06/17 20:05

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
原创粉丝点击