[英]Java : Taking 2 array find if the element that exists in both array return true if exist else false
我正在尋找有關此解決方案的一些說明。 誰能指導我以下兩點:
非常感謝您的澄清。 提前致謝
public static void main(String[] args) {
String[] a = {"a", "b", "c", "d"};
String[] b = {"z", "f", "c"};
boolean value1 = find(a, b);
System.out.println(value1);
boolean value2 = findArray(a, b);
System.out.println(value2);
}
/*
since the both the array is of diff size for nested loop
Big O = O(n*n)
if array size is same Big O = O(n^2)
*/
private static boolean find(String[] a, String[] b) {
for (int i = 0; i < a.length; i++) {
String val1 = a[i];
for (int j = 0; j < b.length; j++) {
if (val1.equals(b[j])) {
System.out.println(val1 + " : " + b[j]);
return true;
}
}// O(n)
}// O(n)
return false;
}// O(n*n)
/*
Big O = O(n)
*/
private static boolean findArray(String[] a, String[] b) {
//create array list from array
List<String> list = new ArrayList<>(Arrays.asList(b));
for (int i = 0; i < a.length; i++) {
String val1 = a[i]; //O(1)
if (list.contains(val1)) {
System.out.println(val1 + " : contain in list b");
return true;
}// O(1)
}// O(n)
return false;
}// O(n)
你的第二個解決方案也是 O(N^2),因為包含在引擎蓋下工作 O(N)。
第一個解決方案 O(N*LogN):
整體復雜度 O(NLogN)
第二種解決方案 O(N) - 如果數組已排序。 如果不是 O(NLogN),因為步驟 1
代碼:
int curA = 0, curB = 0;
while (true) {
if (curA >= a.length || curB >= b.length)
break;
if (a[curA] < b[curB]) {
curA++;
continue;
}
if (a[curA] > b[curB]) {
curB++;
continue;
}
return true;
}
return false;
size、isEmpty、get、set、iterator 和 listIterator 操作在恆定時間內運行。 add 操作在分攤常數時間內運行,即添加 n 個元素需要 O(n) 時間。 所有其他操作都在線性時間內運行(粗略地說)。 與 LinkedList 實現相比,常量因子較低。
https://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.