通过模式,我检查数组是否有重复项。我在这里检查了类似的查询,但他们用包含 ArrayList 和 HashMap 的答案解决了这个问题。我对它们不熟悉并尝试用数组来回答它。我的以下代码仅适用于 1 个重复项,无法执行多个重复项检测。
public class Mode {
public static void main(String[] args) {
int[] num = {2,3,4,5,8,8,8,7,7,7};
int mode = mode(num);
System.out.println(mode);
}
public static int mode(int[] num){
for(int x=0; x < num.length; x++){
for(int y=x+1; y < num.length; y++){
if(num[x] == num[y]){
return num[x];
}
}
}
return num[0];
}
}
最佳答案
方法 mode
应返回 HashSet
包含重复项而不是 int
。另请注意,您的内部循环不正确。你应该这样做:
public static HashSet<Integer> mode(int[] num){
HashSet<Integer> dup = new HashSet<>();
for(int x=0; x < num.length; x++) {
for(int y=0; y < num.length; y++) {
if(num[x] == num[y] && x != y) {
dup.add(num[x]);
}
}
}
return dup;
}
该解的复杂度为 O(n2)。如果您满足以下条件,您可以获得更好的解决方案:
- 对数组进行排序。
- 在上面旅行(仅一次),如果
num[i] == num[i + 1]
,则为重复项。
此解决方案的复杂度为 O(n*log(n)) - 仅在数组上排序和移动一次。
关于java - 检查数组中是否有多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20246068/