[LeetCode] 2582. Pass the Pillow
There are n
people standing in a line labeled from 1
to n
. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.
- For example, once the pillow reaches the
nth
person they pass it to then - 1th
person, then to then - 2th
person and so on.
Given the two positive integers n
and time
, return the index of the person holding the pillow after time
seconds.
Example 1:
Input: n = 4, time = 5 Output: 2 Explanation: People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2. Afer five seconds, the pillow is given to the 2nd person.
Example 2:
Input: n = 3, time = 2 Output: 3 Explanation: People pass the pillow in the following way: 1 -> 2 -> 3. Afer two seconds, the pillow is given to the 3rd person.
Constraints:
2 <= n <= 1000
1 <= time <= 1000
递枕头。
n
个人站成一排,按从1
到n
编号。最初,排在队首的第一个人拿着一个枕头。每秒钟,拿着枕头的人会将枕头传递给队伍中的下一个人。一旦枕头到达队首或队尾,传递方向就会改变,队伍会继续沿相反方向传递枕头。
- 例如,当枕头到达第
n
个人时,TA 会将枕头传递给第n - 1
个人,然后传递给第n - 2
个人,依此类推。给你两个正整数
n
和time
,返回time
秒后拿着枕头的人的编号。
这道题我给出两种思路,一是模拟,二是数学。
模拟的思路是用一个 boolean flag 表示到底是往左走还是往右走,往右走 index++,往左走 index--,走到 index == 1 和 index == n 的时候 flag 要换方向。
时间O(time)
空间O(1)
Java实现
1 class Solution { 2 public int passThePillow(int n, int time) { 3 int index = 1; 4 boolean right = true; 5 while (index >= 1 && index <= n && time != 0) { 6 if (index == n) { 7 index--; 8 right = false; 9 } else if (index == 1) { 10 index++; 11 right = true; 12 } else { 13 index = right == true ? index + 1 : index - 1; 14 } 15 time--; 16 } 17 return index; 18 } 19 }
数学的思路如下。我们如果需要知道最后时间用完的时候走到哪个位置,我们需要知道两个信息,一是到底是往左走还是往右走,二是每走一轮需要消耗多少步。仔细观察,从 1 走到 n 需要 n - 1 步,同样的,从 n 走到 1 也需要 n - 1 步,所以我们可以把 time 除以 (n - 1) 就知道走了几轮,记为 round;把 time 模 (n - 1) 就知道最后一轮(最后一次掉头之后)走了几步,记为 mod。如果 round 是奇数那么说明停下之前是从左往右走的,反之则是从右往左走的。需要知道方向的原因是因为这决定了到底是从左边还是从右边计算最后走了几步。
时间O(1)
空间O(1)
Java实现
1 class Solution { 2 public int passThePillow(int n, int time) { 3 int round = time / (n - 1); 4 int mod = time % (n - 1); 5 if (round % 2 == 1) { 6 return n - mod; 7 } 8 return mod + 1; 9 } 10 }