n
个人站成一排,按从 1
到 n
编号。
最初,排在队首的第一个人拿着一个枕头。每秒钟,拿着枕头的人会将枕头传递给队伍中的下一个人。一旦枕头到达队首或队尾,传递方向就会改变,队伍会继续沿相反方向传递枕头。
- 例如,当枕头到达第
n
个人时,TA 会将枕头传递给第n - 1
个人,然后传递给第n - 2
个人,依此类推。
给你两个正整数 n
和 time
,返回 time
秒后拿着枕头的人的编号。
示例 1:
输入:n = 4, time = 5 输出:2 解释:队伍中枕头的传递情况为:1 -> 2 -> 3 -> 4 -> 3 -> 2 。 5 秒后,枕头传递到第 2 个人手中。
示例 2:
输入:n = 3, time = 2 输出:3 解释:队伍中枕头的传递情况为:1 -> 2 -> 3 。 2 秒后,枕头传递到第 3 个人手中。
提示:
2 <= n <= 1000
1 <= time <= 1000
答:
我们写一个Java函数,计算在给定时间后拿着枕头的人的编号:
public class PillowGame {
public int findPillowOwner(int n, int time) {
int direction = 1; // 初始传递方向,1表示向右,-1表示向左
int currentPerson = 1; // 当前拿着枕头的人的编号
while (time > 0) {
// 如果当前传递方向是向右且当前人是最后一个人,或者向左且当前人是第一个人,改变传递方向
if ((direction == 1 && currentPerson == n) || (direction == -1 && currentPerson == 1)) {
direction *= -1;
}
// 计算下一个拿着枕头的人的编号
if (direction == 1) {
currentPerson++;
} else {
currentPerson--;
}
time--;
}
return currentPerson;
}
public static void main(String[] args) {
PillowGame game = new PillowGame();
int n1 = 4, time1 = 5;
int n2 = 3, time2 = 2;
int result1 = game.findPillowOwner(n1, time1);
int result2 = game.findPillowOwner(n2, time2);
System.out.println("示例1输出:" + result1); // 应该输出2
System.out.println("示例2输出:" + result2); // 应该输出3
}
}