腾讯笔试第三题求指点

腾讯第三题,样例能过但是case0,求大佬指点
import java.util.*;
public class Tencent3 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int N=in.nextInt();
int K=in.nextInt();
HashMap<String,Integer> map=new HashMap<>();
for(int i=0;i<=N;i++){
String s=in.nextLine();
if(s.length()==0){
continue;
}
if(map.containsKey(s)){
map.put(s,map.get(s)+1);
}
else{
map.put(s,1);
}
}
//建立一个map比较器
List<Map.Entry<String,Integer>> list=new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() {
@Override
public int compare(Map.Entry<String,Integer> t1,Map.Entry<String,Integer> t2){
//先按value降序排
if(t1.getValue()<t2.getValue()){
return 1;
}
else if(t1.getValue()>t2.getValue()){
return -1;
}
//相等的时候按key的降序排
else{
return t1.getKey().compareTo(t2.getKey());
}
}
});
for(int i=0;i<K;i++){
System.out.println(list.get(i).getKey()+" "+list.get(i).getValue());
}
Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() {
@Override
public int compare(Map.Entry<String,Integer> t1,Map.Entry<String,Integer> t2){
//先按value升序排
if(t1.getValue()<t2.getValue()){
return -1;
}
else if(t1.getValue()>t2.getValue()){
return 1;
}
//相等的时候按key的降序排
else{
return t1.getKey().compareTo(t2.getKey());
}
}
});
for(int i=0;i<K;i++){
System.out.println(list.get(i).getKey()+" "+list.get(i).getValue());
}
}

}
#腾讯#
全部评论
+ 1,我佛了
点赞
送花
回复 分享
发布于 2020-09-07 15:59
第一行<=N是不是有问题?
点赞
送花
回复 分享
发布于 2020-09-07 16:16
秋招专场
校招火热招聘中
官网直投

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务