https://leetcode.com/problems/number-of-students-unable-to-eat-lunch
1700. Number of Students Unable to Eat Lunch
齁楼提供PM跟MC两种贴贴 分别用0跟1表示
全部齁粉站在一queue 每个齁粉喜欢PM或MC
贴贴数量与齁粉数量相等 贴贴被放在一stack
如果queue前面的齁粉喜欢stack顶端的贴贴 他会拿走贴贴
否则他会放下贴贴并回到queue最后面
循环反复 直至剩下的齁粉都不想拿stack最顶端的贴贴 他们就会去公园
请回传公园民的数量
Example 1:
Input: students = [1,1,0,0], sandwiches = [0,1,0,1]
Output: 0
Explanation:
- Front student leaves the top sandwich and returns to the end of the line
making students = [1,0,0,1].
- Front student leaves the top sandwich and returns to the end of the line
making students = [0,0,1,1].
- Front student takes the top sandwich and leaves the line making students =
[0,1,1] and sandwiches = [1,0,1].
- Front student leaves the top sandwich and returns to the end of the line
making students = [1,1,0].
- Front student takes the top sandwich and leaves the line making students =
[1,0] and sandwiches = [0,1].
- Front student leaves the top sandwich and returns to the end of the line
making students = [0,1].
- Front student takes the top sandwich and leaves the line making students =
[1] and sandwiches = [1].
- Front student takes the top sandwich and leaves the line making students =
[] and sandwiches = [].
Hence all students are able to eat.
Example 2:
Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]
Output: 3
思路1:
模拟两个数列出入过程 假如students里面没有sandwiches[0] 回传student的长度
否则继续模拟 直至students为空 回传0
Python Code:
class Solution:
def countStudents(self, students: List[int], sandwiches: List[int]) ->
int:
while students:
if sandwiches[0] not in students:
return len(students)
f = students.pop(0)
if f == sandwiches[0]:
sandwiches.pop(0)
else:
students.append(f)
return 0
思路2:
先开一个list纪录学生偏好的三明治的数量 之后纪录sandwiches的初始长度
最后遍历sandwiches
假如list[sandwich[0]] == 0 就break
假如初始长度为零 break
否则list[sandwich[0]]-1 初始长度-1
最后回传初始长度
Python Code:
class Solution:
def countStudents(self, students: List[int], sandwiches: List[int]) ->
int:
counts = [0, 0]
for student in students:
counts[student] += 1
remaining = len(sandwiches)
for sandwich in sandwiches:
if counts[sandwich] == 0:
break
if remaining == 0:
break
counts[sandwich] -= 1
remaining -= 1
return remaining