题解 | 小苯送礼物-Java

小苯送礼物

https://www.nowcoder.com/practice/466e02d2177845589ab5fa5decc2857f

import java.util.*;

public class Main {
    static class Fan {
        int support;  // 支持力度 = 点赞数 + 2*收藏数
        int collect;  // 收藏数,用于支持力度相同时的排序
        int id;       // 粉丝编号

        Fan(int support, int collect, int id) {
            this.support = support;
            this.collect = collect;
            this.id = id;
        }
    }

    public static void main(String[] args) {
        // 使用Scanner接收输入
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();

        Fan[] fans = new Fan[n];
        for (int i = 0; i < n; i++) {
            int x = scanner.nextInt();  // 点赞数
            int y = scanner.nextInt();  // 收藏数
            // 计算支持力度并存储粉丝信息
            fans[i] = new Fan(x + 2 * y, y, i + 1);
        }

        // 自定义排序规则
        Arrays.sort(fans, (a, b) -> {
            // 首先按支持力度降序排列
            if (a.support != b.support) {
                return Integer.compare(b.support, a.support);
            }
            // 支持力度相同则按收藏数降序排列
            if (a.collect != b.collect) {
                return Integer.compare(b.collect, a.collect);
            }
            // 前两者都相同则按编号升序排列
            return Integer.compare(a.id, b.id);
        });

        // 提取前k名粉丝的编号
        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = fans[i].id;
        }

        // 按编号升序排序结果
        Arrays.sort(result);

        // 输出结果
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < k; i++) {
            sb.append(result[i]);
            if (i < k - 1) {
                sb.append(" ");
            }
        }
        System.out.println(sb.toString());

        // 关闭Scanner
        scanner.close();
    }
}

全部评论

相关推荐

09-16 17:32
门头沟学院 Java
顺顺超爱学:1.熟悉Java编程语言,熟悉集合,多线程,IO,反射等核心知识,了解线程池,ThreadLocal等进阶知识; 2.熟悉Mysql数据库,熟练使用sql,熟悉索引,存储引擎,事务原理,MVCC,锁机制,了解sql优化; 3.熟悉Redis缓存,了解常见的数据类型,了解缓存常见问题及其解决方案,了解使用Redis实现的分布式锁方案; 4.熟悉Javaweb开发框架,熟悉spring,springmvc,mybatis等,了解IOC,AOP等; 5.熟悉微服务开发框架,熟悉SpringBoot,SpringCloud,包括Nacos,OpenFeign,Gateway等核心组件; 6.熟悉Rabbitmq消息队列,熟练使用消息模型,了解架构,消息可靠性,死信队列,延迟消息等;
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务