为什么这个 break 语句没有按预期工作?

Why doesn't this break statement work as intended?

我有这个带有中断语句的简单代码片段。我试图解决这个 http://codeforces.com/contest/787/problem/B。我想到了这个解决方案:

public static void main(String[] args) {
    FastReader in = new FastReader();
    int n = in.nextInt(), m = in.nextInt();
    HashSet<Integer> set = new HashSet<>();
    for(int i=0;i<m;i++){
        set.clear();
        int k = in.nextInt();
        boolean cancel = true;
        for(int j=0;j<k;j++){
            int cur = in.nextInt();
            if(set.contains(-cur)){
                cancel = false;
                break;
            }
            else set.add(cur);
        }
        if(cancel && k!=0){
            System.out.println("YES");
            return;
        }
    }
    System.out.println("NO");
}

它没有通过测试,但是当我删除 cancel = false 之后的 break 语句时;线。有用。我似乎无法解释使用 break 语句之间的区别,因此当您第一次在 set 中找到 -cur 时,您会将 cancel 更改为 false 然后 break 并在每次在 set 中找到 -cur 时分配 false 以取消并等待直到循环结束而不中断。

当您跳出 for(int j=0;j<k;j++) 时,您不会读取该行输入的所有 k 个数字(除非您已经在最后一个数字处)。

例如,考虑这个输入:

2 2
3 -1 1 -2
1 2

读取-1 和 1 后,您编程将 cancel 设置为 false 并跳出内循环。下次通过外循环时,它会将 -2 读入 k,而你就搞砸了。

删除 break 语句后,您将正确读取所有数字,因此您的程序可以正常运行。