代码之家  ›  专栏  ›  技术社区  ›  Alpit Anand

为什么哈希集显示出奇怪的行为?

  •  2
  • Alpit Anand  · 技术社区  · 7 年前

    我正试图编写一个简单的问题代码。只是为了澄清,而不是一场持续的比赛。 这是密码

        package Algorithms;
    
    import java.util.HashSet;
    import java.util.Scanner;
    
    public class shino {
        public static void main(String args[]){
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            int seq[]= new int[a];
            int count=0;
            for(int j=0;j<a;j++){
                seq[j] = sc.nextInt();
            }
            HashSet<HashSet> hashSets = new HashSet<>();
    
    
                for(int y=0;y<seq.length;y++){
    
                    for(int u=0;u<seq.length;u++){
    
                        HashSet<Integer> hash = new HashSet<>();
                        int q =Math.abs(y-u);
                        if(y!=u && q==1 ) {
    
                            hash.add(seq[y]);
                            hash.add(seq[u]);
                        }
                        if(hashSets.add(hash)){
                            System.out.println(seq[y]+" "+seq[u]);
                            count++;
                        }
                    }
                }
                System.out.println(count);
    
        }
    }
    

    现在你可以看到 Y!= U 但是当我把输入作为

    5
    1 2 3 4 5
    

    它的输出是

    1 1
    1 2
    2 3
    3 4
    4 5
    5
    

    为什么有双人间 1 1 在上面? 我真的不明白我做错了什么? 老实说,我确实有一些编程经验,但我真的不明白为什么会这样?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Hovercraft Full Of Eels    7 年前

    您首先添加的是空哈希集,如果布尔测试不好,则只允许有一个哈希集表明您的第二个哈希集:

    HashSet<Integer> hash = new HashSet<>();
    int q =Math.abs(y-u);
    if(y!=u && q==1 ) {
        hash.add(seq[y]);
        hash.add(seq[u]);
    }
    if(hashSets.add(hash)){
        System.out.println(seq[y]+" "+seq[u]);
        count++;
    }
    

    相反,将所有内容放在第一个if块中:

    HashSet<Integer> hash = new HashSet<>();
    int q = Math.abs(y-u);
    if(y != u && q == 1 ) {
        hash.add(seq[y]);
        hash.add(seq[u]);
    
        System.out.println(seq[y] + " " + seq[u]);
        count++;
    }
    

    注:为什么要测试 y != u 从那以后 q == 1 Y 不能 等于u

    更好的是:

    if (q == 1) {
        hash.add(seq[y]);
        hash.add(seq[u]);
    
        System.out.println(seq[y] + " " + seq[u]);
        count++;
    }