LeetCode 2582. Pass the pillow: explain the O(1) time algorithm in clear words

【LetMeFly】2582. Pass the pillow: explain the O(1) time algorithm in clear words

Leetcode question link: https://leetcode.cn/problems/pass-the-pillow/

nIndividuals stand in a row and are numbered from 1to 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 nperson, TA will pass the pillow to the -th n - 1person, then to the -th n - 2person, and so on.

Given two positive integers nand time, return timethe 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

Method 1: Calculate

n people pass pillows, and n − 1 n-1 need to be passed from left to rightn1 time. In the same way, n − 1 n-1needs to be passed from right to left.n1 time. That is,2 × ( n − 1 ) 2\times(n-1)2×(n1 ) Cycle once.

Therefore, time timet im e directly modulo the last2 × ( n − 1 ) 2\times(n-1)2×(n1 ) is equivalent to the result of a single round of transmission.

  • If time ≤ n − 1 time\leq n-1timen1 , it means it is passing to the right. Pass0 00 times at1 11 , pass1 11 time in2 22,…,传 t i m e time t im e times are attime + 1 time + 1time+1

  • Otherwise, it means passing to the left. Passed to the left time − ( n − 1 ) time - (n - 1)time(n1 ) times. Pass to the left0 00 times innnn , pass to the left1 11 time atn − 1 n-1n1 ,..., pass to the lefttime − ( n − 1 ) time - (n - 1)time(n1)次处于 n − ( t i m e − ( n − 1 ) ) = 2 ∗ n − t i m e − 1 n - (time - (n - 1)) = 2 * n - time - 1 n(time(n1))=2ntime1

  • Time complexity O ( 1 ) O(1)O(1)

  • Space complexity O ( 1 ) O(1)O(1)

AC code

C++
class Solution {
    
    
public:
    int passThePillow(int n, int time) {
    
    
        time %= (n - 1) * 2;
        return time <= n - 1 ? time + 1 : 2 * n - time - 1;
    }
};
Python
class Solution:
    def passThePillow(self, n: int, time: int) -> int:
        time %= (n - 1) * 2
        return time + 1 if time <= n - 1 else 2 * n - time - 1

The article is published simultaneously on CSDN. It is not easy to be original. Please attach the link to the original article after reprinting with the author's consent ~
Tisfy: https://letmefly.blog.csdn.net/article/details/133294825

Guess you like

Origin blog.csdn.net/Tisfy/article/details/133294825