英文 |
翻译 | web前端开发(ID:web_qdkf)
给定两个包含数组元素的数组,任务是检查两个数组是否包含任何公共元素,然后返回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:暴力破解方法
// 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))
输出:
false
时间复杂度:O(M * N)
方法2:
例:
// 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))
输出:
false
时间复杂度:O(M + N)
方法3:
<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
限 时 特 惠: 本站每日持续更新海量各大内部创业教程,一年会员只需98元,全站资源免费下载 点击查看详情
站 长 微 信: lzxmw777
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。