数组中出现次数超过一半的数字

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

代码

import java.util.HashMap;
import java.util.Map;
public class Solution {
       public int MoreThanHalfNum_Solution(int [] array) {
        int num = 0;

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

        }
        return num;
    }
}

总结

  • map的遍历方式
  • 使用map存储出现次数的映射关系
  • map.put(key,value)
posted @ 2019-02-24 15:16  crr121  阅读(95)  评论(0编辑  收藏  举报