LeetCode 1385번 Find the Distance Value Between Two Arrays JavaScript

찌니월드·2025년 4월 22일

문제

Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.

The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.

문제 출처

1385. Find the Distance Value Between Two Arrays

나의 풀이

var findTheDistanceValue = function(arr1, arr2, d) {
    arr2.sort((a, b) => a - b);
    let count = 0;

    for (let i = 0; i < arr1.length; i++) {
        let isValid = true;
        let left = 0;
        let right = arr2.length - 1;

        while (left <= right) {
            let mid = Math.floor((left + right) / 2);

            if (Math.abs(arr1[i] - arr2[mid]) <= d) {
                isValid = false;
                break;
            }

            if (arr2[mid] < arr1[i]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        if (isValid) count++;
    }

    return count;
};
profile
Front-End Developer

0개의 댓글