假设我有 2 个这样的数组:let x = [1,3,4,7,10]
和另一个这样的数组 let y = [0,4,6,9,12]
我将如何检查以 1 分隔的数组中是否有任何值?例如,第一个数组中的 3 个,第二个数组中的 4 个。它们由一分隔,因此返回 true。我正在寻找它返回一个布尔值。
答案 0 :(得分:3)
这种方法迭代两个数组,但需要排序数组。
在迭代时,它首先取较小的值,尽管是数组。
如果找到两个增量为 1 的值,则函数 check
返回 true
,否则返回 false
。
function check(a, b) {
let i = 0,
j = 0;
do {
console.log(a[i], b[j]);
if (a[i] + 1 === b[j] || a[i] === b[j] + 1) return true;
if (a[i] <= b[j] && i + 1 < a.length) i++;
else j++;
} while (j < b.length)
return false;
}
console.log(check([1, 3, 4, 7, 10], [0, 4, 6, 9, 12])); // true
console.log(check([1, 2, 3, 4, 5], [6, 9, 12, 13, 14])); // true
console.log(check([6, 9, 12, 13, 14], [1, 2, 3, 4, 5])); // true
console.log(check([1, 2, 3, 4, 5], [7, 9, 12, 13, 14])); // false
console.log(check([7, 9, 12, 13, 14], [1, 2, 3, 4, 5])); // false
console.log(check([3, 4], [3]));
console.log(check([3], [3, 4]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:2)
我能想到的最好的是
true
false
在 JS 中的实现应该是这样的:
function eliminateDuplicates(arr) {
return arr.filter((v, i) => arr.indexOf(v) === i);
// Removes every single item that has a different indexOf index than its own
// This is a clever technique i found on https://medium.com/dailyjs/how-to-remove-array-duplicates-in-es6-5daa8789641c
}
function anyItemsWithDiffrence1(arr1, arr2, eliminateDuplicates) {
if (eliminateDuplicates) {
arr1 = eliminateDuplicates(arr1);
arr2 = eliminateDuplicates(arr2);
}
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
if (Math.abs(arr[i] - arr[j]) === 1) return true;
// We check if the absolute difference between the two items is 1
}
}
return false;
}