快速判斷某一個數組是否是另一個數組的子集
阿新 • • 發佈:2019-01-06
給定兩個無序陣列:陣列arr1[0…m-1] 和 陣列arr2[0…n-1] ,判斷陣列arr2是否是arr1的子集。
比如
arr1[] = {11, 1, 13, 21, 3, 7}
arr2[] = {11, 3, 7, 1}
輸出true
arr1[] = {1, 2, 3, 4, 5, 6},
arr2[] = {1, 2, 4}
輸出true
arr1[] = {10, 5, 2, 23, 19}
arr2[] = {19, 5, 3}
輸出false
方法1
使用兩個for迴圈。外部迴圈挑選出arr2[]的每一個元素賦值為value;然後再內部迴圈中,搜尋在arr1[]中是否存在value。如果arr2[]中的每一個元素都可以在arr1[]中被找到,則返回true
false
。具體程式碼如下:
boolean isSubset(int arr1[], int arr2[], int m, int n) { int i = 0; int j = 0; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) if(arr2[i] == arr1[j]) break; /* If the above inner loop was not broken at all then arr2[i] is not present in arr1[] */ if (j == m) return false; } /* If we reach here then all elements of arr2[] are present in arr1[] */ return true; }
方法2
1 先將兩個陣列分別進行排序
2 然後用Merge Type(合併型別)的過程, 判斷arr2[]是否是arr1[]的子集
boolean isSubset(int arr1[], int arr2[], int m, int n) { int i = 0, j = 0; if(m < n) return false; Arrays.sort(arr1); //sorts arr1 Arrays.sort(arr2); // sorts arr2 while( i < n && j < m ) { if( arr1[j] < arr2[i] ) j++; else if( arr1[j] == arr2[i] ) { j++; i++; } else if( arr1[j] > arr2[i] ) return false; } if( i < n ) return false; else return true; }
因為要對兩個陣列分別進行排序,所以時間複雜度為O(mLogm + nLogn)
方法3(使用HashSet)
1 建立一個HashSet,並將陣列arr1[]中的所有元素儲存到此HashSet中
2 遍歷arr2[], 並在HashSet中搜索arr2[]的每一個元素. 如果某一個元素沒有找到則返回0.
3 如果arr2[]中的每一個元素都可以在HashSet中找到,則返回1
boolean isSubset(int arr1[], int arr2[], int m, int n)
{
HashSet<Integer> hset= new HashSet<>();
// hset stores all the values of arr1
for(int i = 0; i < m; i++)
{
if(!hset.contains(arr1[i]))
hset.add(arr1[i]);
}
// loop to check if all elements of arr2 also
// lies in arr1
for(int i = 0; i < n; i++)
{
if(!hset.contains(arr2[i]))
return false;
}
return true;
}