所以基本上,我有一个数组,有十个值......
int[] input = new int[10];
Run Code Online (Sandbox Code Playgroud)
用户控制每个值的输入.
检查数组中的任何值是否等于任何其他值的好方法是什么?
编辑:
public static void main(String[] args) {
P2 numbers = new P2();
for (int i = 0; i < numbers.input.length; i++) {
numbers.input[i] = numbers.scan.nextInt();
}
numbers.Check();
if (numbers.Check()) { System.out.println("Duplicate"); }
if (numbers.Check() == false) { System.out.println("NOT Duplicate"); }
}
public boolean Check() {
int length = input.length;
for(int i : input) {
for(int j = i + 1; j < length; j++) {
if(input[i] == input[j]) return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
只要重复的数字是索引邻居,代码就可以工作.
如果你在数组中只有10个值,那么你最好使用双嵌套循环,当它找到重复时会中断.
int length = input.length;
for(int i = 0; i < length; i++) {
for(int j = i + 1; j < length; j++) {
if(intput[i] == input[j]) return true;
}
}?
Run Code Online (Sandbox Code Playgroud)
如果您希望扩展到一个大数目,那么最好填充一个hashset并在找到已经存在于Hashset中的值时断开.
HashSet<Integer> set = new HashSet<Integer>();
for(int i : input) {
if(set.contains(i)) return true;
set.add(i);
}?
Run Code Online (Sandbox Code Playgroud)