华为2022.4.6笔试第一题
华为2022.4.6笔试第一题
m是文章个数,每一篇文章有一行标题和一行正文,一共有2m行字符串。单词出现在文章,该单词频率+3,单词出现在正文,该单词频率+1
对单词排序:先看频率,频率大放前面,如果频率一样,看单词在标题出现的频率,大的放前面,都一样看谁出现的早。输出前n个单词
public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); HashMap<String,Integer> title = new HashMap<>(); HashMap<String,Integer> text = new HashMap<>(); HashMap<String,Integer> order = new HashMap<>(); HashSet<String> looks = new HashSet<>();//出现了那些单词 int k = 0; sc.nextLine(); for (int i=0;i<2*m;i++){ String s = sc.nextLine(); String[] words = s.split(" "); for (String word : words){ looks.add(word); if(!order.containsKey(word)){ order.put(word, k++); } if(i%2==0){ title.put(word,title.getOrDefault(word, 0)+3); }else { text.put(word,text.getOrDefault(word,0)+1); } } } PriorityQueue<String> p = new PriorityQueue<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { int o1_title = title.getOrDefault(o1, 0); int o1_text = text.getOrDefault(o1, 0); int o2_title = title.getOrDefault(o2,0); int o2_text = text.getOrDefault(o2,0); int k1 = order.get(o1); int k2 = order.get(o2); //小堆 if(o2_title+o2_text < o1_text+o1_title){ return 1; }else if(o2_title+o2_text > o1_text+o1_title){ return -1; }else { if(o2_title < o1_title){ return 1; }else if(o2_title > o1_title){ return -1; }else { return k2 - k1;//出现位置靠后的放在堆顶 } } } }); for (String look : looks){ if(p.size()<n){ p.add(look); }else { p.add(look); p.poll(); } } LinkedList<String> list = new LinkedList<>(); while (p.size()>0){ String tmp = p.poll(); list.addFirst(tmp); } for (int i=0;i<n;i++){ String tmp = list.get(i); if(i==n-1){ System.out.println(tmp); }else { System.out.print(tmp+" "); } } } }