For each element from arr1 try against all elements in arr2.
If arr1 has elements and
arr2 has elements, time:
, space:
.
class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
count = 0
for x in arr1:
count += (1 if all( abs(x-y) > d for y in arr2 ) else 0)
return count
Insight: For a number in
nums1, if the closest number in nums2 is and
, then all other numbers in
nums2 must also be more than distance away from
.
If nums2 were sorted, we could use binary-search to find in
time. Because,
lo always points to where a number should have been inserted in sorted order. So, should be at
lo-1 or lo.
Time: . Space would be that of sorting.
class Solution:
def find_closest(self, x, nums) -> int:
lo, hi = 0, len(nums)-1
while lo <= hi:
mid = (lo+hi) // 2
if x == nums[mid]:
return x
if x < nums[mid]:
hi = mid-1
else:
lo = mid+1
left = nums[lo-1] if lo > 0 else float('-inf')
right = nums[lo ] if lo < len(nums) else float('inf')
return left if x-left <= right-x else right
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
arr2.sort()
count = 0
for x in arr1:
y = self.find_closest(x, arr2)
count += (1 if abs(x-y) > d else 0)
return count
Leave a comment