數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。
package com.example.study;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
*author:bingbing
*日期:2020年7月4日
*時間:下午3:12:46
*數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。
*/
public class demo03 {
public static void main(String[] args) {
int a[]=new int[] {1, 2, 3, 2, 2, 2, 5, 4, 2};
Map<Integer,Integer> countMap=new HashMap<Integer,Integer>();
int count=0;
System.out.println(Arrays.toString(a));
for(int i=0;i<a.length;i++) {
if(countMap.containsKey(a[i])) {
countMap.put(a[i], countMap.get(a[i])+1);
}else {
countMap.put(a[i], count+1);
}
}
//找出map中key對應的value的值大於數組長度一半的值。
int length=a.length/2;
for(Object key:countMap.keySet()) {
if(countMap.get(key)>length) {
System.out.println("該數字爲:"+key);
}
}
}
}