【题目】
【代码】
class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
cnt=0
arr2=set(arr2)
for item1 in arr1:
list1=set([i+item1 for i in range(1,d+1)]+[item1])|set([-i+item1 for i in range(1,d+1)])
if len(list1 & arr2)==0:
cnt+=1
return cnt
【方法2】O(n^2)两层循环
class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
cnt=0
for item1 in arr1:
if all(abs(item1-item2)>d for item2 in arr2):
cnt+=1
return cnt
【方法3】二分法
class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
arr2.sort()
cnt = 0
for x in arr1:
p = bisect.bisect_left(arr2, x)
if p == len(arr2) or abs(x - arr2[p]) > d:
if p == 0 or abs(x - arr2[p - 1]) > d:
cnt += 1
return cnt