#纪念机试挂掉##华为机试#
4.06 0分
第一道
输出最高权数的前几位字符串
题目欢迎大家补充,
我贴贴我的代码
package com.letcode;
import java.util.*;
public class Comparedemo {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int a=Integer.parseInt(sc.nextLine());
int b=Integer.parseInt(sc.nextLine());
HashMap<String,Word> map=new HashMap<>();
TreeSet<Word> set=new TreeSet<>(new compare());//暂未用到
TreeMap<Word,Integer> map1=new TreeMap<>(new compare());//暂未用到
PriorityQueue<Word> q=new PriorityQueue<>(new compare());//暂未用到
//(o1, o2) -> o1.k-o1.k>0 ? -1:1
for(int i=0;i<2*a;i++){
String [] w=sc.nextLine().split(" ");
Word word;
for(int j=0;j<w.length;j++) {
if (!map.containsKey(w[j])) {
//若不存在该字符,则生成一个对象,若存在,则取出。
word = new Word();
word.name = w[j];
map.put(w[j], word);
} else {
word = map.get(w[j]);
}
word.setK();
if (i % 2 == 0) {
//处理标题行
word.setK1();
if (word.getI1() == -1) {
word.setI1(j);
}
} else {
//处理正文
word.setK2();
if (word.getI2() == -1) {
word.setI2(j);
}
}
}
}
for(String e:map.keySet()){
set.add(map.get(e));
map1.put(map.get(e),map.get(e).k);
q.offer(map.get(e));
}
for(int i=0;i<b;i++){
System.out.println(set.pollFirst().toString());
}
}
static class Word{
String name;
int k=0;//该词出现的总数
int i1=-1;//该词在标题行首次出现的位置,如标题行没有,默认-1;
int k1=0;//标题行出现的次数
int i2=-1;//在正文中首次出现的位置
int k2=0;//正文中出现的次数
public String toString(){
//toString
return this.name;
}
public void setK() {
//设置出现总次数
this.k++;
}
public int getI1() {
return i1;
}
public void setI1(int i1) {
this.i1 = i1;
}
public void setK1() {
this.k1 ++;
}
public int getI2() {
return i2;
}
public void setI2(int i2) {
this.i2 = i2;
}
public void setK2() {
this.k2 ++;
}
}
static class compare implements Comparator<Word>{
@Override
//比较器
public int compare(Word o1, Word o2) {
if(o1.k !=o2.k){
return o2.k-o1.k;
//返回总次数大的
}else{
if(o1.k1!=o2.k1){
//返回标题行次数大的
return o2.k1-o1.k1;
}else{
if(o1.k2!=o2.k2){
//返回正文行出现次数大的
return o2.k2- o1.k2;
}else{
if(o1.i1!=o2.i1){
// 返回标题位置出现靠前的
return o1.i1-o2.i1;
}else{
if(o1.i2!=o2.i2){
//返回正文出现靠前的
return o1.i2-o2.i2;
}else {
//默认返回字符小的在前。
return -1;
}
}
}
}
}
}
}
}
/*
输入
2
5
xin wde de
we e ded dedlk dlkn de d xinx nddk dedkjklnd ded de xinguan xinahun xin xisd xin d dindeid dejeb
fire ef in de
dnw de fire de ff defe e ef e fe e fe esd de d edsd de edi f
2
3
a b
c d a d
a c
d c d c
2
5
we in wei
in sun in sun sun in we in
sun io we we
wei du sun we w in sun e ei ie ei
* */#笔试题目##华为#
