剑指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
- 剑指offer(二十四)之数组中出现次数超过一半的数字
- (二十一)剑指offer之数组中出现次数超过一半的数字
- 剑指offer之二十二---数组中出现次数超过一半的数字
- 剑指offer--数组中出现次数超过一半的数字
- 《剑指offer》数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- 【剑指Offer】数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字||剑指offer
- 剑指offer 数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- [剑指offer]数组中出现次数超过一半的数字
- 《剑指offer》-数组中出现次数超过一半的数字
- 剑指offer|数组中出现次数超过一半的数字
- 剑指offer-数组中出现次数超过一半的数字
- 《剑指offer》数组中出现次数超过一半的数字
- 剑指offer - 数组中出现次数超过一半的数字
- 剑指Offer:数组中出现次数超过一半的数字
- ZooKeeper典型应用场景一览
- 【模板】二叉树合集
- ceshi
- hdoj BestCoder Round #81 (div.2) AA Machine
- mysql百万级别数据查询心得
- 剑指offer(二十四)之数组中出现次数超过一半的数字
- nginx的yum安装方法
- VS2010中为OpenCV工程创建属性单
- 【dp】NOIP2010提高组乌龟棋
- <css 十八>图片的透明
- Knight Moves(HDU 1372)(BFS)
- 新手必须掌握的Linux命令
- ExpandableListView的使用
- 类加载器