我想检查数组或列表中的所有相似整数是否都分组了。
{2, 2, 5, 5, 5, 1, 7, 7, 5, 7}
应该给出 false
。而 {2, 2, 5, 5, 5, 1, 7, 7, 7}
应该给出 true
。这是我目前所拥有的,它在应该为 false
时打印 true
:
public class testing1 {
public static void main(String[] args){
int [] x = {2, 2, 5, 5, 5, 1, 7, 7, 5, 7};
System.out.println(isGrouped(x));
}
public static boolean isGrouped(int[] x){
for(int i = 0; i < x.length; i++){
for(int j = i + 1; j < x.length; j++){
if(x[i] == x[j])
return true;
}
}
return false;
}
}
最佳答案
正如其他答案中提到的那样,您的答案并没有考虑到所有情况,因此不适用于许多情况。另外,这里不需要 2 个循环。您可以将已经看到的元素存储在散列中,并为列表中的每个元素存储它是否第一次出现。如果它不是第一次出现并且之前的元素与此不同,那么它应该是 false。
代码如下:
public class testing1 {
public static void main(String[] args){
int [] x = {2, 2, 5, 5, 5, 1, 7, 7, 5, 7};
System.out.println(isGrouped(x));
}
public static boolean isGrouped(int[] x){
int prev = x[0] ;
Hashtable<Integer, Integer> hashtable =
new Hashtable<Integer, Integer>();
hashtable.put(x[0], 0);
for (int i = 1 ; i < x.length ; i ++)
{
if (hashtable.get(x[i]) != null && prev == x[i]){
hashtable.put(x[i], hashtable.get(x[i]) + 1);
}
else if (hashtable.get(x[i]) != null && prev != x[i]){
return false;
}
else{
hashtable.put(x[i], 0);
}
prev = x[i];
}
return true ;
}
}
这也存储了每个元素出现的次数。 希望这会有所帮助:)
关于java - 如何检查数组中的所有重复项是否已分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46137833/