剑指offer_【28】数组中出现次数超过一半的数字

1.题目描述

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

2.解题思路

利用一个hashmap用来存储数组里面每个数出现的次数,然后遍历map,比较每个数的value是否超过数组的一半

3.代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
HashMap<Integer,Integer> map = new HashMap<>();
int res = 0;
for(int i = 0;i<array.length;i++){
if(map.containsKey(array[i])){
map.put(array[i],map.get(array[i])+1);
}else{
map.put(array[i],1);
}
}
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
if(entry.getValue()>array.length/2)
res = entry.getKey();
}
return res;
}
}
文章目录
  1. 1. 1.题目描述
  2. 2. 2.解题思路
  3. 3. 3.代码
| 139.6k