方法一 暴力循环
枚举arr1里每个元素,看是否对于arr2里的元素差值的绝对值都大于d
var findTheDistanceValue = function(arr1, arr2, d) {
let count =0
for(let num1 of arr1){
let flag=true
for(let num2 of arr2){
let dis=Math.abs(num1-num2)
if(dis<=d){
flag=false
}
}
if(flag) count++
}
return count
};
消耗时间和内存情况:
方法二 二分查找
先将arr2数组进行排序,然后在arr2里找arr1数组里的元素的位置,也就是找arr2里最接近arr1元素 的两个元素,如果这两个元素和arr1的元素差值都大于d,那么其他元素都该满足。
var findTheDistanceValue = function (arr1, arr2, d) {
arr2.sort((a, b) => a - b);
let count = 0;
for (let num of arr1) {
let flag = true;
let idx = searchIdx(arr2, num);
if (idx - 1 >= 0) {
flag = flag & Math.abs(num - arr2[idx - 1]) > d;
}
if (idx < arr2.length) {
flag = flag & Math.abs(num - arr2[idx]) > d;
}
if (flag) count++;
}
return count;
};
var searchIdx = function (arr2, i) {
let left = 0;
let right = arr2.length - 1;
while (left <= right) {
let mid = left + Math.floor((right - left) >> 1);
if (arr2[mid] < i) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
消耗时间和内存情况: