题解 | #排队购票#

排队购票

https://www.nowcoder.com/practice/44f07b72cd574485b0296a40eca83215

import java.util.*;

class Visitor implements Comparable<Visitor> {
    int id;
    int time;

    public Visitor(int id, int time) {
        this.id = id;
        this.time = time;
    }

    @Override
    public int compareTo(Visitor other) {
        return Integer.compare(this.time, other.time);
    }
}

public class Solution {

    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param numTickets int整型
     * @param visitorTimes int整型一维数组
     * @return int整型一维数组
     */
    public int[] ticketQueue (int numTickets, int[] visitorTimes) {
        // write code here
        // Create an array of Visitor objects with IDs and ticket times
        Visitor[] visitors = new Visitor[numTickets];
        for (int i = 0; i < numTickets; i++) {
            visitors[i] = new Visitor(i + 1, visitorTimes[i]);
        }

        // Sort visitors based on ticket times
        Arrays.sort(visitors);

        // Create a result array to store the order of ticket purchase
        int[] result = new int[numTickets];
        for (int i = 0; i < numTickets; i++) {
            result[i] = visitors[i].id;
        }

        return result;
    }
}

创建了一个 Visitor 数组,将每个游客对象添加到数组中,并按照购票所需时间进行排序。最后,它将排序后的游客的编号添加到结果数组中,并将结果数组返回。

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务