题解 | #编程题2#

编程题2

https://www.nowcoder.com/practice/43068a1013b4417a85c2c2ce8b18159e

import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);

        while(in.hasNext()){
            solution(in);
        }
    }

    /**
     * 模拟法
     * 
     * distribute -> room_i
     * 不论room_i的位置在哪里,其房间内再分配后的人数总是最少的.
     * 如果出现多个房间内人数都与最少人数相同的情况,那么从room_x向前推,第一个人数最少的房间即为room_i.
     * 
     * @param in
     */
    private static void solution(Scanner in){
        // 房间数量
        int total = in.nextInt();
        // 最后一个人被分配的房间号
        int lastIn = in.nextInt();
        // 每个房间人数, 从1开始
        long[] rooms = new long[total+1];
        // 房间的最少人数
        long pMin = Integer.MAX_VALUE;

        for(int i=1; i<=total; i++){
            rooms[i] = in.nextLong();
            pMin = Math.min(pMin, rooms[i]);
        }

        // 已重新分配的房间号,即: 房间号lastIn(包含lastIn)前面人数最少的房间号
        int distribute = lastIn;
        while(rooms[distribute] != pMin){
//            distribute = (distribute>1) ? distribute-1 : total;
            distribute = (distribute-2+total)%total+1;
        }

        if(distribute < lastIn){
            for(int i=1; i<=total; i++){
                if(i < distribute){
                    rooms[i] -= pMin;
                }else if(i == distribute){
                    rooms[i] = pMin*total+(lastIn-distribute);
                }else if(distribute<i && i<=lastIn){
                    rooms[i] -= (pMin+1);
                }else{
                    rooms[i] -= pMin;
                }
            }
        }

        if(distribute == lastIn){
            for(int i=1; i<=total; i++){
                if(i != distribute){
                    rooms[i] -= pMin;
                }else{
                    rooms[i] = pMin*total;
                }
            }
        }

        if(distribute > lastIn){
            for(int i=1; i<=total; i++){
                if(i <= lastIn){
                    rooms[i] -= (pMin+1);
                }else if(lastIn<i && i<distribute){
                    rooms[i] -= pMin;
                }else if(i == distribute){
                    rooms[i] = pMin*total+(lastIn)+(total-distribute);
                }else{
                    rooms[i] -= (pMin+1);
                }
            }
        }

        for(int i=1; i<=total; i++){
            System.out.print(rooms[i]+" ");
        }
    }
}

全部评论

相关推荐

07-07 11:33
江南大学 Java
已经在暑假实习了&nbsp;,没有明确说有hc,纠结实习到八月份会不会有点影响秋招毕竟感觉今年好多提前批
程序员小白条:92的话准备提前批,其他没必要,没面试机会的,而且你要准备充分,尤其八股和算法题
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 13:35
虽然不怎么光彩,经过这件事,可能我真的要去认同“面试八股文早该淘汰!不会用AI作弊的程序员=新时代文盲!”这句话了
HellowordX:Ai的出现是解放劳动力的,不是用来破坏公平竞争环境的,这样下去,轻则取消所有线上面试,严重了会影响整个行业对所有人产生影响,企业会拉高入职考核各种离谱考核会层出不穷
你找工作的时候用AI吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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