1227. Airplane Seat Assignment Probability
- Airplane Seat Assignment Probability python solution
题目描述
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 passengers will:
Take their own seat if it is still available,
Pick other seats randomly when they find their seat occupied
What is the probability that the n-th person can get his own seat?
解析
我们考虑n>1的情况
当第一个人到来坐在了位置k上,那么第(2到k-1)的人会坐在他们本身的位置上。所以第k个人就有3种选择,
(1)选择坐在第一个位置上,那么第n个人肯定会坐在位置n上
(2)选择坐在第n个位置上,那么第n个人无法坐在属于自己的位置上
(3)选择坐在k+1到n的位置中间
如果他选择了(3)那么会陷入循环。假设他选择了位置j,则第j个人会面临同样的选择。而选择(1)和选择(2)是等概率,所以最终的概率应该是0.5
class Solution:
def nthPersonGetsNthSeat(self, n: int) -> float:
if(n==1):
return(1.0)
else:
return(0.5)
Reference
https://leetcode.com/problems/airplane-seat-assignment-probability/discuss/407707/O(1)-space-O(1)-runtime-with-intuitive-explanation.