Directory link:
Likou Programming Questions-Solution Summary_Sharing + Recording-CSDN Blog
GitHub synchronous question brushing project:
https://github.com/September26/java-algorithms
Original title link: LeetCode official website - the technology growth platform loved by geeks around the world
describe:
n
Individuals stand in a row and are numbered from to 1
to n
.
Initially, the first person at the head of the line holds a pillow. Every second, the person holding the pillow passes the pillow to the next person in line. Once the pillow reaches the beginning or end of the line, the direction of the delivery changes and the team continues passing pillows in the opposite direction.
- For example, when the pillow reaches the th
n
person, TA will pass the pillow to the thn - 1
person, then to the thn - 2
person, and so on.
Given the sum n
of two positive integers time
, return time
the number of the person holding the pillow seconds later.
Example 1:
Input: n = 4, time = 5 Output: 2 Explanation: The pillow delivery situation in the team is: 1 -> 2 -> 3 -> 4 -> 3 -> 2. After 5 seconds, the pillow is passed to the second person.
Example 2:
Input: n = 3, time = 2 Output: 3 Explanation: The pillow delivery situation in the team is: 1 -> 2 -> 3. After 2 seconds, the pillow is passed to the third person.
hint:
2 <= n <= 1000
1 <= time <= 1000
Problem-solving ideas:
First, take the remainder from (n-1)*2, because (n-1)*2 represents one round and does not affect the result.
Then just distinguish the process from 1 to N, and just the process from N to 1.
Code:
class Solution {
public:
int passThePillow(int n, int time) {
time = time%((n-1)*2);
if(time/(n-1)%2 == 0){
return time+1;
}else{
return 2*n-time-1;
}
}
};