Easy 169题 Majority Element

来源:互联网 发布:常用排序算法 编辑:程序博客网 时间:2024/05/06 21:28

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.


Solution:

sort is always a good idea for may array problem , but we prefer to use hashmap here and we should pay attention to the difference between Integer and int

public class Solution {    public int majorityElement(int[] nums) {        /*This is amazing.......*/        /*        Arrays.sort(nums);        return nums[nums.length / 2];        */        /*Hash*/        HashMap<Integer, Integer> res = new HashMap<>();        int ans=0;        int n=nums.length;        int i=0;        Iterator iter = res.entrySet().iterator();        for(i=0;i<=n-1;i++)        {           if(!res.containsKey(nums[i]))                res.put(nums[i],1);            else            {                int tmp=res.get(nums[i]).intValue()+1;                res.put(nums[i],tmp);            }        }        iter = res.entrySet().iterator();        while(iter.hasNext())        {            Map.Entry entry = (Map.Entry) iter.next();            if((int)(entry.getValue())>Math.floor(n/2))                ans=(int)(entry.getKey());        }        return ans;    }}


0 0
原创粉丝点击