腾讯笔试第三题求指点
腾讯第三题,样例能过但是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());
}
}
}
#腾讯#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());
}
}
}