Day 02| 小红书24后端两题:小红的分享日常&小红书推荐系统

114 阅读1分钟

15.小红的分享日常

15小红.png

思路

一个01背包问题 但是需要练习acm格式下的输入输出的练习

01-背包

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        int numCount = in.nextInt(); // 物品数量
        int t = in.nextInt(); // 背包的时间
        int totalHappy = in.nextInt(); // 背包的幸福值

        int[][] nums = new int[numCount][2]; // 物品的消耗时间和体力
        long[] happy = new long[numCount]; // 物品的幸福值

        // 读取物品的信息
        for (int i = 0; i < numCount; i++) {
            nums[i][0] = in.nextInt(); // 消耗时间
            nums[i][1] = in.nextInt(); // 消耗体力
            happy[i] = in.nextLong(); // 幸福值
        }
        
        // dp[i][j] 表示在时间为 i,体力为 j 时的最大幸福值
        long[][] dp = new long[t + 1][totalHappy + 1];
        
        // 遍历所有物品
        for (int i = 0; i < numCount; i++) {
            int timeCost = nums[i][0]; // 物品的时间消耗
            int energyCost = nums[i][1]; // 物品的体力消耗
            long happyValue = happy[i]; // 物品的幸福值
            
            // 从后往前更新 dp 数组,避免之前的状态影响后续计算
            for (int m = t; m >= timeCost; m--) {
                for (int n = totalHappy; n >= energyCost; n--) {
                    // 当前物品可以放入背包
                    dp[m][n] = Math.max(dp[m][n], dp[m - timeCost][n - energyCost] + happyValue);
                }
            }
        }
        
        System.out.println(dp[t][totalHappy]); // 输出背包的最大幸福值
    }
}

2.小红书推荐系统

2推荐系统.png

思考

哈希表

import java.util.Scanner;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        String[] ch = s.split(" ");

        HashMap<String,Integer> map = new HashMap<>();
        for(String c:ch){
            map.put(c,map.getOrDefault(c,0)+1);
        }
        List<Map.Entry<String,Integer>> list = new ArrayList();
        for(Map.Entry<String,Integer> entry:map.entrySet()){
            if(entry.getValue()>=3){
                list.add(entry);
            }
        }
        Collections.sort(list,(o1,o2)->{if(o2.getValue()==o1.getValue()){return o1.getKey().compareTo(o2.getKey());}return o2.getValue()-o1.getValue();});
        for(Map.Entry<String,Integer> entry:list){
            System.out.println(entry.getKey());
        }
    }
}