当前位置: 代码迷 >> 综合 >> 给定一个整型数组arr,请打印其中出现次数大于一半的数,如果没有这样的数,请输出-1
  详细解决方案

给定一个整型数组arr,请打印其中出现次数大于一半的数,如果没有这样的数,请输出-1

热度:59   发布时间:2024-01-27 06:37:53.0

public class Main{

 // 用map来存储各个数据出现的次数
public static Map<Integer, Integer> map;
// 用number来存储数据的个数
public static int number;


    // 数据初始化
public static void init(){
Scanner s = new Scanner(System.in);
map = new HashMap<Integer, Integer>();
number = s.nextInt();
s.nextLine();
for(int i=0; i<number; i++){
int temp = s.nextInt();

    // 如果map中存在该数据
if(map.containsKey(temp)){
map.replace(temp, map.get(temp) + 1);
}


      // 否则添加 (key, value) = (temp, 1)
else{
map.put(temp, 1);
}
}
s.close();
}

public static void print(){
int count = 0;
int half = number / 2;
Iterator<Integer> iterator = map.keySet().iterator();
while(iterator.hasNext()) {
int key = iterator.next();
int temp = map.get(key);
if(temp > half) {
count ++;
System.out.println(key);

     // 找到该数后就break任务
break;
}
}

if(count == 0) {
System.out.println(-1);
}

}
public static void main(String[] args){
init();
print();
}
}

  相关解决方案