0 和 1 表示。
students 和 sandwiches,其中 sandwiches[i] 是栈里面第 i 个三明治的类型(i = 0 是栈的顶部),students[j] 是初始队列里第 j 名学生对三明治的喜好(j = 0 是队列的最开始位置)
students 数组存入队列 q 中,一次遍历就把队列中所有元素访问一次,只要某一次遍历后队列的大小不变就认为循环结束,否则就一直循环遍历。【其余行为就是在模拟题目,不断取出 q 的头部并与 sandwiches 数组的头部比较】students 中 1 和 0 的个数,而一次遍历 sandwiches 就可以确定结果;遍历停止的条件就是 sandwiches 的头部元素的剩余学生个数为零,例如当前头部元素为 1,而剩余学生中 1 的个数为零,则此时剩余所有学生都不喜欢栈顶的三明治。class Solution
{
public:
int countStudents(vector<int>& students, vector<int>& sandwiches)
{
queue<int> q;
for(int num : students) q.push(num);
int idx = 0;
while(1)
{
int sz = q.size();
for(int i = 0; i < sz; ++i)
{
int tmp = q.front(); q.pop();
if(tmp == sandwiches[idx]) ++idx;
else q.push(tmp);
}
if(q.size() == sz) return sz;
}
return 0;
}
};