题解 | 无法吃午餐的学生数量

无法吃午餐的学生数量

https://www.nowcoder.com/practice/2dac3d7567f741a88ec551caf907934d

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param students int整型一维数组 
# @param sandwiches int整型一维数组 
# @return int整型
#
class Solution:
    def countStudents(self , students: List[int], sandwiches: List[int]) -> int:
        # write code here
        # 法1:
        # n=len(students)
        # for _ in range(n*n):
        #     #当学生队列为空,证明所有人都拿到了,返回0
        #     if len(students)==0:
        #         return 0
        #     #记录拿到了的
        #     if students[0]==sandwiches[0]:
        #         students.pop(0)
        #         sandwiches.pop(0)
        #     #没有拿到的人拍最后去
        #     else:
        #         students.append(students.pop(0))
        # #返回没有拿到的学生数
        # return len(students)

        # 法2
        i=0#记录当前三明治与多少个学生没有匹配上
        while i<len(students):#当前三明治没匹配的人数等于学生数时,退出循环
            if students[0]==sandwiches[0]:
                students.pop(0)
                sandwiches.pop(0)
                i=0#记录下一个三明治
            else:
                i+=1#学生与当前三明治没匹配上
                students.append(students.pop(0))
        return len(students)

全部评论

相关推荐

狸猫换offer:神通广大的互联网
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务