前言:
接下来主要做一做数组方面的题。前面有几篇博客是关于数组的,有点乱了,我在这里标注一下,方便观看。
删除数组中重复的数字
顺时针打印矩阵
调整数组顺序使奇数位于偶数前面
二维数组中查找某个值
构建乘积数组
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
解题思路
最开始看这道题,想到的是使用排序算法,先排序一下,然后在统计,最后比较。我们这样是比较麻烦。所以我就想到了HashMap。用HashMap来存储,数字用来做key,统计出现的次数作为value,并同时比较出现次数最多的key。使用这种方法,好想,代码也挺简单的,最后成功AC,所以在这里分享一下这个方法。
代码样例
package com.asong.leetcode.MoreThanHalfNum_Solution;
import java.util.HashMap;
/**
* 数组中出现次数超过一半的数字
* 思路: 利用HashMap存储并统计,将最大的一个比较出来,然后进行比较。
*/
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array==null||array.length==0)
{
return 0;
}
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
int middle = array.length/2;
int max=0;
int save_key = 0;
for (int i = 0; i < array.length; i++) {
if(map.get(array[i]) == null)
{
map.put(array[i],1);
}else {
map.put(array[i],map.get(array[i])+1);
}
max = Math.max(max,map.get(array[i]));
if(max == map.get(array[i]))
{
save_key = array[i];
}
}
/* for (Integer key:map.keySet()
) {
max = Math.max(max,map.get(key));
if(max == map.get(key))
{
save_key = key;
}
}*/
if(max>middle)
{
return save_key;
}else {
return 0;
}
}
public static void main(String[] args) {
int[] array = {1,2,3,2,2,2,5,4,2};
Solution solution = new Solution();
int res = solution.MoreThanHalfNum_Solution(array);
System.out.println(res);
}
}