[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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人