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

一、题目

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

二、解法

 1 import java.util.HashMap;
 2 public class Solution {
 3     public int MoreThanHalfNum_Solution(int [] array) {
 4          HashMap<Integer,Integer> hasharray = new HashMap();
 5             for(int i = 0; i < array.length; i++){
 6                 Integer temp = hasharray.get(array[i]);//从hashmap中获取值
 7                 if(temp == null){//如果没有,则添加到hashmap中去
 8                     hasharray.put(array[i], 1);
 9                     temp = 1;
10                 }else{
11                     hasharray.put(array[i],++temp);
12                 }
13                 if(temp >= array.length/2+1) return array[i];
14             }
15             return 0;
16     }
17 }

 

posted @ 2017-08-30 15:06  fankongkong  阅读(131)  评论(0编辑  收藏  举报