当前位置:网站首页>The distance value between two arrays of LeetCode simple questions
The distance value between two arrays of LeetCode simple questions
2022-07-31 03:02:00 【·The sea of stars】
题目
给你两个整数数组 arr1 , arr2 和一个整数 d ,请你返回两个数组之间的 距离值 .
「距离值」 定义为符合此距离要求的元素数目:对于元素 arr1[i] ,不存在任何元素 arr2[j] 满足 |arr1[i]-arr2[j]| <= d .
示例 1:
输入:arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
输出:2
解释:
对于 arr1[0]=4 我们有:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
所以 arr1[0]=4 符合距离要求
对于 arr1[1]=5 我们有:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
所以 arr1[1]=5 也符合距离要求
对于 arr1[2]=8 我们有:
|8-10|=2 <= d=2
|8-9|=1 <= d=2
|8-1|=7 > d=2
|8-8|=0 <= d=2
存在距离小于等于 2 的情况,不符合距离要求
故而只有 arr1[0]=4 和 arr1[1]=5 两个符合距离要求,距离值为 2
示例 2:
输入:arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
输出:2
示例 3:
输入:arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
输出:1
提示:
1 <= arr1.length, arr2.length <= 500
-10^ 3 <= arr1[i], arr2[j] <= 10^3
0 <= d <= 100
来源:力扣(LeetCode)
解题思路
根据题目的要求可知,数组1The elements in are and arrays respectively2Find the absolute distance of the elements in ,如果数组1an element in an array2All elements of the distance meet the requirements,Then it can be counted as 1.A simple idea here is to convert arrays2排序,then look at the array1The elements in should be in the array2中的位置,Then probe the distance between the two elements before and after it,If these two distances meet the requirements, then the remaining elements naturally meet the requirements.
class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
arr2.sort()
count=0
for i in arr1:
index=bisect.bisect(arr2,i)
if index==0:
if abs(i-arr2[index])>d:
count+=1
elif index==len(arr2):
if abs(i-arr2[index-1])>d:
count+=1
else:
if abs(i-arr2[index-1])>d and abs(i-arr2[index])>d:
count+=1
return count
边栏推荐
- 10、Redis实现点赞(Set)和获取总点赞数
- C#远程调试
- 【CocosCreator 3.5】CocosCreator 获取网络状态
- Intel's software and hardware optimization empowers Neusoft to accelerate the arrival of the era of smart medical care
- 华为分布式存储FusionStorage知识点总结【面试篇】
- 【异常】The field file exceeds its maximum permitted size of 1048576 bytes.
- CorelDRAW2022精简亚太新增功能详细介绍
- 【C语言】三子棋(经典解法+一览图)
- String为什么不可变?
- Mysql 45讲学习笔记(二十四)MYSQL主从一致
猜你喜欢
随机推荐
你们程序员为什么不靠自己的项目谋生?而必须为其他人打工?
观察者模式
Chapter 9 SVM实践
6. Display comments and replies
YOLOV5学习笔记(二)——环境安装+运行+训练
MultipartFile文件上传
TCP详解(三)
The whole process scheduling, MySQL and Sqoop
什么是分布式锁?实现分布式锁的三种方式
16、热帖排行
开题报告之论文框架
Graphical lower_bound & upper_bound
工程(五)——小目标检测tph-yolov5
注解用法含义
CorelDRAW2022 streamlined Asia Pacific new features in detail
原子操作 CAS
【C语言】进制转换一般方法
SQL injection Less47 (error injection) and Less49 (time blind injection)
CefSharp入门-winform
Modbus on AT32 MCU