我正在尝试编写一个简单的问题。只是为了澄清,这不是一场正在进行的比赛。 这是代码
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? 我真的不明白我在这里做错了什么? 说实话,我确实有一些编程经验,但我真的不明白为什么会发生这种情况?
最佳答案
您首先添加空的 HashSet,并且只允许添加一个,这表明您的第二个 if boolean 测试不好:
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 block 中:
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++;
}
关于java - 为什么哈希集表现出奇怪的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50669750/