剑指offer(二十四)之数组中出现次数超过一半的数字

来源:互联网 发布:php 今日头条 编辑:程序博客网 时间:2024/06/05 01:13
题目描述

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

思路分析:

   创建一个HashMap,key--数组元素,value--数组元素出现的个数;用Iterator和Map.Entry进行循环,取key,value值。

具体代码:

<span style="font-family:SimSun;font-size:24px;">import java.util.*;public class Solution {    public int MoreThanHalfNum_Solution(int [] array) {         int len=array.length;         int result=0;         HashMap map=new HashMap();         for(int i=0;i<len;i++){             if(!map.containsKey(array[i])){                 map.put(array[i],1);             }else{                 int num=(int)map.get(array[i]);                 map.put(array[i],++num);             }         }         int size=(len%2==0?len/2:len/2+1);         Iterator<Map.Entry> it=map.entrySet().iterator();         while(it.hasNext()){             Map.Entry entry=it.next();             if((int)entry.getValue()>=size){                 result=(int)entry.getKey();             }         }         return result;     }}</span>


0 0