小红书后端

牛客网 - 找工作神器|笔试题库|面试经验|实习招聘内推,求职就业一站解决_牛客网 (nowcoder.com)

小红书推荐系统

题目:

思路:

尝试(标题4)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        Map<String,Integer> map = new HashMap<>();
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            String str = in.next();
            if(!map.containsKey(str)){
                map.put(in.next(),1);
            }else{
                int i = map.get(str);
                map.put(str,i+1);
            }
        }
        for(EntrySet entry : map.get()){
            if(map.get(entry)>=)
        }
    }
}
答案
import java.util.*;

public class Main{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 读取输入
        String input = scanner.nextLine();
        // 将输入按空格分割
        String[] words = input.split(" ");
        
        // 使用Map来统计每个单词的出现频率
        Map<String, Integer> wordCount = new HashMap<>();
        for (String word : words) {
            wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }
        
        // 使用List来存储满足条件的单词
        List<String> keywords = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
            if (entry.getValue() >= 3) {
                keywords.add(entry.getKey());
            }
        }
        
        // 自定义比较器,首先按频次降序排序,其次按字典序升序排序
        keywords.sort((a, b) -> {
            int freqA = wordCount.get(a);
            int freqB = wordCount.get(b);
            if (freqA != freqB) {
                return freqB - freqA;
            } else {
                return a.compareTo(b);
            }
        });
        
        // 输出结果
        for (String keyword : keywords) {
            System.out.println(keyword);
        }
        
        scanner.close();
    }
}
小结
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值