leetcode 169. Majority Element

来源:互联网 发布:sql服务器无法启动 编辑:程序博客网 时间:2024/06/06 15:45

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.

就是使用HashMap直接计数。

代码如下:

import java.util.HashMap;import java.util.Map;public class Solution {    public int majorityElement(int[] nums)     {        Map<Integer, Integer> map=new HashMap<Integer, Integer>();        for(int i=0;i<nums.length;i++)            map.put(nums[i], map.getOrDefault(nums[i], 0)+1);        for (Integer key : map.keySet())         {              if(map.get(key) >= (nums.length+1)/2)                return key;        }         return 0;    }}

下面是C++的做法,就是使用map做一次遍历操作

代码如下:

#include <iostream>#include <vector>#include <string>#include <map>using namespace std;class Solution{public:    int majorityElement(vector<int>& nums)    {        map<int, int> mmp;        for (int a : nums)        {            if (mmp.find(a) == mmp.end())                mmp[a] = 1;            else                mmp[a] += 1;        }        for (map<int, int>::iterator i = mmp.begin(); i != mmp.end(); i++)        {            if (i->second >= (nums.size() + 1) / 2)                return i->first;        }        return 0;    }};
原创粉丝点击