题解 | 小红书推荐系统
小红书推荐系统
https://www.nowcoder.com/practice/e5b39c9034a84bf2a5e026b2b9b973d0
朴实无华的排序,频率相同按字典序排序,否则按频率降序排序
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String line = in.nextLine();
String[] arr = line.split(" ");
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
}
ArrayList<KeyWord> list = new ArrayList<>();
map.forEach((k, v) -> {
if(v >= 3) list.add(new KeyWord(k, v));
});
list.sort((o1, o2) -> {
if(o1.freq == o2.freq) return o1.key.compareTo(o2.key);
else return o2.freq - o1.freq;
});
list.forEach(e -> System.out.println(e.key));
}
}
class KeyWord {
String key;
int freq;
public KeyWord(String key, int freq) {
this.key = key;
this.freq = freq;
}
}
查看1道真题和解析