学校的自助午餐提供圆形和方形的三明治,分别用数字 0 和 1 表示。所有学生站在一个队列里,每个学生要么喜欢圆形的要么喜欢方形的。
餐厅里三明治的数量与学生的数量相同。所有三明治都放在一个 栈 里,每一轮:
如果队列最前面的学生 喜欢 栈顶的三明治,那么会 拿走它 并离开队列。
否则,这名学生会 放弃这个三明治 并回到队列的尾部。
这个过程会一直持续到队列里所有学生都不喜欢栈顶的三明治为止。
给你两个整数数组 students 和 sandwiches ,其中 sandwiches[i] 是栈里面第 i 个三明治的类型(i = 0 是栈的顶部), students[j] 是初始队列里第 j 名学生对三明治的喜好(j = 0 是队列的最开始位置)。请你返回无法吃午餐的学生数量。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-students-unable-to-eat-lunch
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
模拟 | 队列
class Solution {
public int countStudents(int[] students, int[] sandwiches) {
Queue<Integer> queue = new ArrayDeque<>();
for(int i=0;i<students.length;++i){
queue.offer(students[i]);
}
//添加
for (int i = 0; i < sandwiches.length; ++i ){
boolean judge=false;
for(int j=0;j<queue.size() && judge==false;++j){
if(sandwiches[i]==queue.peek()){
judge=true;
queue.poll();
}else{
queue.offer(queue.poll());
}
}
if(judge==false){
return queue.size();
}
}
return queue.size();
}
}
数学分析
解析:
因为学生可以循环排队,所以分面包的结果只有两种:
- 都分完了
- 没有分完,剩下的学生不是0就是1
所以先统计学生中0与1的个数,遍历面包减少学生
当学生出现负数时说明那个类型的分完了,所以这时候剩下的学生就是本该饿肚子的学生,所以返回数量即可。
class Solution {
public int countStudents(int[] students, int[] sandwiches) {
int num0 = 0, num1 = 0;
for (int i = 0; i < students.length; ++i) {
if (students[i] == 0)
num0++;
else
num1++;
}
for(int i=0;i<sandwiches.length;++i){
if(sandwiches[i]==0)
num0--;
else
num1--;
if(Math.min(num0,num1)==-1)
return Math.max(num0,num1);
}
return 0;
}
}