2073.买票需要的时间
方法一:使用队列
class Solution {public int timeRequiredToBuy(int[] tickets, int k) {Queue<TicketBuyer> queue = new LinkedList<>();for(int i = 0;i<tickets.length;i++){TicketBuyer buyer = new TicketBuyer();buyer.index = i;buyer.ticketCnt = tickets[i];queue.add(buyer);}int time = 0;while(!queue.isEmpty()){TicketBuyer first = queue.poll();first.ticketCnt--;time++;if(first.ticketCnt!=0){queue.offer(first);}else if(first.index == k){break;}}return time;}// 买票者信息private class TicketBuyer {// 索引位private Integer index;// 要购买票数private Integer ticketCnt;}
}
方法二:遍历分析
class Solution {public int timeRequiredToBuy(int[] tickets, int k) {int n = tickets.length;int res = 0;for(int i = 0; i<n ;i++){if(i<=k){ //这个人初始在第k个人的前方,或者恰好是第k个人res += Math.min(tickets[i],tickets[k]); //在第k个人买完票之前,最多可以购买tickets[k]张票,所以时间是两者最小值}else{ //这个人初始在第k个人的后方res += Math.min(tickets[i],tickets[k] - 1); //在第k个人买完票之前,最多可以购买tickets[k]-1张票}}return res;}
}