蒜头君面试

练习题:蒜头君面试
Description

蒜头君来蒜厂面试的时候,曾经遇到这样一个面试题:

给定n个整数,求里面出现次数最多的数,如果有多个重复出现的数,求出值最大的一个。当时可算是给蒜头君难住了。现在蒜头君来考考你。

Input
第一行输入一个整数n(1≤n≤100000),接下来一行输入n个 int 范围内的整数。

Output
输出出现次数最多的数和出现的次数,中间用一个空格隔开,如果有多个重复出现的数,输出值最大的那个。

Sample Input 1

5
1 1 2 3 4
Sample Output 1

1 2
Sample Input 2

10
9 10 27 4 9 10 3 1 2 6
Sample Output 2

10 2

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<n;i++){
int num=sc.nextInt();
if(map.containsKey(num)){
map.put(num, map.get(num)+1);
}
else{
map.put(num, 1);
}
}
int maxKey=0;
int maxValue=0;
for(Map.Entry<Integer, Integer> entry:map.entrySet()){
if(entry.getValue()>maxValue){
maxKey=entry.getKey();
maxValue=entry.getValue();
}
else if(entry.getValue()==maxValue&&entry.getKey()>maxKey){
maxKey=entry.getKey();
maxValue=entry.getValue();
}
}
System.out.println(maxKey+" "+maxValue);
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值