Majority Element

来源:互联网 发布:双十一淘宝海报尺寸 编辑:程序博客网 时间:2024/06/05 10:15

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.

public class Solution {    public int majorityElement(int[] num) {        int len = num.length;HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();for(int i=0;i<len;++i){if(!map.containsKey(num[i])){map.put(num[i], 1);if(len == 1)return num[i];}else {map.put(num[i], map.get(num[i])+1);if(map.get(num[i]) > len/2)return num[i];}}for(Map.Entry<Integer, Integer> entry:map.entrySet()){int key = entry.getKey();int count = entry.getValue();if(count >=len/2)return key;}return -1;            }}


0 0
原创粉丝点击