給定兩個包含數(shù)組元素的數(shù)組妇垢,任務(wù)是檢查兩個數(shù)組是否包含任何公共元素,然后返回True宰衙,否則返回False平道。
Input: array1 = ['a', 'b', 'c', 'd', 'e']
array2 = ['f', 'g', 'c']
Output: true
Input: array1 = ['x', 'y', 'w', 'z']
array2 = ['m', 'n', 'k']
Output: false
對于這個問題,有許多方法可以解決JavaScript中的此問題供炼,下面討論其中一些方法一屋。
方法1:暴力破解方法
- 比較第一個數(shù)組中的每個項目和第二個數(shù)組中的每個項目。
- 遍歷array1并從頭到尾進(jìn)行迭代袋哼。
- 遍歷array2并從頭到尾進(jìn)行迭代冀墨。
- 比較從array1到array2的每個項目,如果找到任何公共項目涛贯,則返回true诽嘉,否則返回false。
<script>
// Declare two array
const array1 = ['a', 'b', 'c', 'd'];
const array2 = ['k', 'x', 'z'];
// Function definiton with passing two arrays
function findCommonElement(array1, array2) {
// Loop for array1
for(let i = 0; i < array1.length; i++) {
// Loop for array2
for(let j = 0; j < array2.length; j++) {
// Compare the element of each and
// every element from both of the
// arrays
if(array1[i] === array2[j]) {
// Return if common element found
return true;
}
}
}
// Return if no common element exist
return false;
}
document.write(findCommonElement(array1, array2))
</script>
輸出:
false
時間復(fù)雜度: O(M * N)
方法2:
- 創(chuàng)建一個空對象并遍歷第一個數(shù)組。
- 檢查第一個數(shù)組中的元素是否存在于對象中虫腋。如果不存在骄酗,則在數(shù)組中分配屬性===元素。
- 遍歷第二個數(shù)組悦冀,并檢查第二個數(shù)組中的元素是否在創(chuàng)建的對象上存在趋翻。
- 如果元素存在,則返回true雏门,否則返回false嘿歌。
例:
<script>
// Declare Two array
const array1 = ['a', 'd', 'm', 'x'];
const array2 = ['p', 'y', 'k'];
// Function call
function findCommonElements2(arr1, arr2) {
// Create an empty object
let obj = {};
// Loop through the first array
for (let i = 0; i < arr1.length; i++) {
// Check if element from first array
// already exist in object or not
if(!obj[arr1[i]]) {
// If it doesn't exist assign the
// properties equals to the
// elements in the array
const element = arr1[i];
obj[element] = true;
}
}
// Loop through the second array
for (let j = 0; j < arr2.length ; j++) {
// Check elements from second array exist
// in the created object or not
if(obj[arr2[j]]) {
return true;
}
}
return false;
}
document.write(findCommonElements2(array1, array2))
</script>
輸出:
false
時間復(fù)雜度: O(M + N)
方法3:
- 使用內(nèi)置的ES6函數(shù)some()遍歷第一個數(shù)組的每個元素并測試該數(shù)組。
- 在第二個數(shù)組中使用內(nèi)置函數(shù)include()來檢查元素是否在第一個數(shù)組中茁影。
- 如果元素存在宙帝,則返回true,否則返回false
<script>
// Declare two array
const array1= ['a', 'b', 'x', 'z'];
const array2= ['k', 'x', 'c']
// Iterate through each element in the
// first array and if some of them
// include the elements in the second
// array then return true.
function findCommonElements3(arr1, arr2) {
return arr1.some(item => arr2.includes(item))
}
document.write(findCommonElements3(array1, array2))
</script>
輸出:
true