LeetCode 1385. Find the Distance Value Between Two Arrays
Question
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
.
Example
1 | Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2 |
Solution
因为是第一题,一般不会难,只需要认真读题目。
题目定义两个数组,假设包含m和n个元素。即m中任意一个都需要和n个数做绝对差值,然后看m中有多少个与全部n元素的差值大于d,则结果加1。其中可以优化的地方则是一旦找到小于等于d的情况就break,停止继续计算。
Code
1 | // time:O(mn) space:O(1); |