原题链接:1385. 两个数组间的距离值
solution: 暴力法
class Solution {
public:
int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) {
int n = arr1.size(), m = arr2.size();
int res = 0;
for(int i=0;i<n;i++){
int cnt = 0;
for(int j=0;j<m;j++){
if(abs(arr1[i]-arr2[j]) > d) cnt++;
}
if(cnt == m) res++;
}
return res;
}
};
二分:自己写的二分搜索,可以替换成lower_bound
class Solution {
public:
int binarySearch(vector<int> &arr,int target) //二分查找
{
int l = 0,r = arr.size()-1;
while (l < r ){
int mid = l + r >> 1;
if (arr[mid] >= target ) r = mid;
else l = mid + 1;
}
return l;
}
int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) {
int n = arr1.size();
sort(arr2.begin(),arr2.end()); //默认升序
int res = 0; //返回值
for(int i = 0;i < n;i++){
int flag = 0; //判断标志位
int index = binarySearch(arr2,arr1[i]); //利用二分在arr2中找到第一个大于等于arr1[i]的数
if(abs(arr1[i] - arr2[index]) > d) flag = 1;
else continue; //如果不满足这个条件直接进入下一次循环
if(index >= 1){
if(abs(arr1[i] - arr2[index-1]) > d) flag = 1;
else flag = 0;
}
res+=flag;
}
return res;
}
};