This can be solved without deque structure
Solution#
- Since all elements in array are either
0or1, So I use the arrayprefer(int[2])to count how many students prefer each type of sandwich - Using
0as an example, while iterating through thesandwichesif the current sandwich is0but no student prefers it, then no one can take the sandwich. At that point, I return the number of remaining students who prefer the other type as the answer.
class Solution {
public int countStudents(int[] students, int[] sandwiches) {
int[] prefer = new int[2];
for (int student : students) {
prefer[student]++;
}
for (int sandwich : sandwiches) {
if (prefer[sandwich] <= 0) return prefer[1 - sandwich];
prefer[sandwich]--;
}
return 0;
}
}