comments | difficulty | edit_url | tags | ||||
---|---|---|---|---|---|---|---|
true |
Medium |
|
n
passengers board an airplane with exactly n
seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
- Take their own seat if it is still available, and
- Pick other seats randomly when they find their seat occupied
Return the probability that the nth
person gets his own seat.
Example 1:
Input: n = 1 Output: 1.00000 Explanation: The first person can only get the first seat.
Example 2:
Input: n = 2 Output: 0.50000 Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
Constraints:
1 <= n <= 105
Let
When
When
When
-
The first passenger has a probability of
$\frac{1}{n}$ to choose the first seat, then all passengers can sit in their own seats, so the probability of the $n$th passenger sitting in their own seat is 1.0. -
The first passenger has a probability of
$\frac{1}{n}$ to choose the $n$th seat, then the second to the $(n-1)$th passengers can sit in their own seats, the $n$th passenger can only sit in the first seat, so the probability of the $n$th passenger sitting in their own seat is 0.0. -
The first passenger has a probability of
$\frac{n-2}{n}$ to choose the remaining seats, each seat has a probability of$\frac{1}{n}$ to be chosen. Suppose the first passenger chooses the $i$th seat, where$2 \le i \le n-1$ , then the second to the $(i-1)$th passengers can sit in their own seats, the seats of the $i$th to the $n$th passengers are uncertain, the $i$th passenger will randomly choose from the remaining$n-(i-1)=n-i+1$ seats (including the first seat and the $(i+1)$th to the $n$th seats). Since the number of remaining passengers and seats is$n-i+1$ , and 1 passenger will randomly choose a seat, the problem size is reduced from$n$ to$n-i+1$ .
Combining the above three cases, we can get the recursive formula of
In the above recursive formula, there are
If you directly use the above recursive formula to calculate the value of
Replace
In the above recursive formula, there are
When
Subtract the above two formulas:
After simplification, we get the simplified recursive formula:
Since we know that
From this, we can get the result of
The time complexity of this solution is
class Solution:
def nthPersonGetsNthSeat(self, n: int) -> float:
return 1 if n == 1 else 0.5
class Solution {
public double nthPersonGetsNthSeat(int n) {
return n == 1 ? 1 : .5;
}
}
class Solution {
public:
double nthPersonGetsNthSeat(int n) {
return n == 1 ? 1 : .5;
}
};
func nthPersonGetsNthSeat(n int) float64 {
if n == 1 {
return 1
}
return .5
}
function nthPersonGetsNthSeat(n: number): number {
return n === 1 ? 1 : 0.5;
}
impl Solution {
pub fn nth_person_gets_nth_seat(n: i32) -> f64 {
return if n == 1 { 1.0 } else { 0.5 };
}
}