思路
由题意当某个学生不喜欢栈顶的三明治时,会退到队列最后,但是栈顶的三明治不会变动,所以可以知道学生的位置不是那么重要,只要还有要吃栈顶三明治的学生存在,那么他就一定能吃到。
因此,我们只需要记录吃三明治1
的学生数量x
,以及吃三明治0
的学生数量y
。
遍历sandwiches
数组,遍历到1
则x--
,遍历到0
则y--
。当若遍历到1
时x == 0
,则说明已经没有学生能吃了,直接退出循环;遍历到0
且y == 0
同理。计算sandwiches
剩余元素数量即可。
代码如下:
class Solution {
public:
int countStudents(vector<int>& students, vector<int>& sandwiches) {
//只需要去判断当前三明治是否还有人吃即可,学生所在位置不重要
int x = accumulate(students.begin(), students.end(), 0); //吃1的数量
int y = students.size() - x; //吃0的数量
int i;
for(i=0; i<sandwiches.size(); ++i){
if(sandwiches[i] == 1 && x > 0){
x--;
} else if(sandwiches[i] == 0 && y > 0){
y--;
} else {
break;
}
}
return sandwiches.size() - i;
}
};