我写这段代码是为了显示只属于任何一个数组的元素。我们可以提高效率吗?
public class App {
public static void main(String[] args){
int[] a = {1,2,3,4,5,6,7,8,9};
int[] b = {1,20,3,4,15,13,6,7,8,12};
for(int i = 0; i < a.length; i++){
int temp = a[i];
for(int j = 0; j < b.length; j++){
if(b[j] == temp){
b[j] = -1;
a[i] = -1;
}
}
if(a[i] != -1)
System.out.print(a[i] + " ");
}
for(int i = 0; i < b.length; i++){
if(b[i] != -1)
System.out.print(b[i] + " ");
}
}
}
最佳答案
是的。确实。
目前,您有一个 O(m * n)
,其中 m
是数组 a
的大小,n
是数组 b
的大小。
将第一个数组中的数据复制到 hashset
(O(n)
操作,其中 n
是 a< 的大小
)。然后,解析第二个数组,检查数据是否在 hashset
中(O(1)
操作)。
考虑对第二个数组执行相同的操作。
关于java - 显示两个数组中不属于两个数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40851539/