题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
当时看到题目的时候,想的是,将数组元素全部添加到一个map中,数组元素为key,value值初始为1,当key值相同时,value+1,最后查找map中的value最大值,接着再根据最大值去找key。
代码很简单,如下。
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0;i<array.length;i++) {
//当map中存在相同的key时,value+1,不存在时将key加入并设value=1
if(map.containsKey(array[i])) {
int value = map.get(array[i]);
map.put(array[i], value+1);
}else {
map.put(array[i], 1);
}
}
int maxValueOfMap =(int) getMaxValue(map);
if(maxValueOfMap > array.length/2) {
return getKeyByValue(map,maxValueOfMap);
}
return 0;
}
public static Object getMaxValue(Map<Integer, Integer> map) {
if (map == null) return null;
Collection<Integer> c = map.values();
Object[] obj = c.toArray();
Arrays.sort(obj);
return obj[obj.length-1];
}
public int getKeyByValue(Map<Integer, Integer> map,int maxValueOfMap) {
for(int key:map.keySet()) {
if(maxValueOfMap==map.get(key))
return key;
}
return 0;
}
public static void main(String[] args) {
int[] array = new int[] {
1,2,3,2,2,2,5,4,2
};
Solution solution = new Solution();
System.out.println(solution.MoreThanHalfNum_Solution(array));
}
}
后面去看了一下别人的解答,才知道什么叫牛逼!!!
https://www.nowcoder.com/profile/519263/codeBookDetail?submissionId=1520973
它的代码如下:
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int len=array.length;
if(len<1){
return 0;
}
int count=0;
//这种形式是对一个数组的所有元素进行排序,并且是按从小到大的顺序
Arrays.sort(array);
int num=array[len/2];
for(int i=0;i<len;i++){
if(num==array[i])
count++;
}
if(count<=(len/2)){
num=0;
}
return num;
}
}
利用数组排序,如果前一半的值,如果数组元素有超过一半的,那么这个num肯定是会等于这个array的array[array.length / 2]的。遍历数组,如果数组中与num相同的count(计数)加一,当count大于等于数组长度的一半时,返回当前值,如果不是,则返回零。简单,明了,学习了。