import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param students int整型一维数组 * @param sandwiches int整型一维数组 * @return int整型 */ public int countStudents (int[] students, int[] sandwiches) { // write code here Deque<Integer> stackDeque=new ArrayDeque<>(); Queue<Integer> queue=new ArrayDeque<>(); for (int i = sandwiches.length-1; i >=0 ; i--) { stackDeque.push(sandwiches[i]); } for (int i = 0; i < students.length; i++) { queue.add(students[i]); } int flag=0; while(!stackDeque.isEmpty()) { if(queue.peek()==stackDeque.peek()) { queue.poll(); stackDeque.pop(); flag=0; }else { int a=queue.poll(); queue.add(a); flag++; if(flag==queue.size()) { break; } } } return queue.size(); } }
这题既然说了队列和栈,那么就先创建出对应的队列和栈,并且把数组中的元素按要求存进去,此时要注意栈的存入是反着的。
存完之后就可以进行操作了,如果栈非空,那么就一直执行操作,知道队列的长度与不符合条件的人数相等时,也就是flag==queue.size(),那么就说明该结束了