LeetCode知识点总结 - 1385

LeetCode 1385. Find the Distance Value Between Two Arrays

考点难度
SortingEasy
题目

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.

思路

arr2排序,用binary search找到距离arr1[i]最近的数。

答案
class Solution {
    public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
        Arrays.sort(arr2);
        int res = 0;
        
        for(int i=0;i<arr1.length;i++)
        {
            int close = findClosest(arr2,arr1[i]);
            if(Math.abs(arr1[i]-close) > d)
                res++;
        }
        
        return res;
    }
    int findClosest(int[] arr,int target)
    {
        int d = Integer.MAX_VALUE;
        int low = 0,high = arr.length-1;
        while(low <= high)
        {
            int mid = low + (high - low)/2;
            if(arr[mid] == target)
                return arr[mid];
            else if(arr[mid] < target)
            {
                low = mid+1;
            }
            else 
            {
                high = mid-1;
            }
            d = Math.abs(target-arr[mid]) < Math.abs(target-d) ? arr[mid] : d;
        }
        return d;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值