Majority Element

来源:互联网 发布:淘宝首页全屏装修教程 编辑:程序博客网 时间:2024/04/24 02:45

题目描述:给定一个数组,输出出现次数超过数组长度半数的数字。

public class Solution {    public int majorityElement(int[] num) {        int halfLen = num.length/2;        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();                for(int i:num) {        int cnt = hashMap.get(i)==null?1:hashMap.get(i)+1;            hashMap.put(i, cnt);            if(halfLen < cnt)            return i;        }        return 1;    }}


0 0
原创粉丝点击