小球投盒(美团2024届秋招笔试第三场编程真题)

核心思想
用一个set存储还没有球的盒子
一旦有2操作 那就剩下1个盒子没有球
代码
import java.util.*;
public class Main {
public static void main(String[] args) {
TreeSet<Integer> q = new TreeSet<>();
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
for(int i = 1; i <= n; i++)
q.add(i);
int res = -1;
boolean flag = false;
for(int i = 1; i <= m ;i++){
int t = scanner.nextInt();
int x = scanner.nextInt();
if(t == 1){
q.remove(x);
}
else{
if(q.contains(x)){
q.clear();
q.add(x);
}else {
q.clear();
}
}
if(q.isEmpty()){
res = i;
break;
}
}
System.out.println(res);
}
}

浙公网安备 33010602011771号