快手算法面试题:求从两个有序数组选出两个数,能得出的最小差值,取绝对值

/**
 * 快手算法面试题:
 * 求从两个有序选出两个数,能得出的最小差值,取绝对值
 * 知识点:变种二分法,寻找边界
 * 时间复杂度:O(nlogn)
 */
public class Main {
    public static void main(String[] args) {
        int[] arr1 = {1,2,676};
        int[] arr2 = {3,5,7};
        System.out.println(new Main().fun(arr1, arr2));
    }
    
    public int fun(int[] a,int[] b){
        int res = -1;
        for(int i = 0; i < a.length;i++){
            if(b[b.length / 2] > a[i]){
                int leftBound = leftSearch(b,a[i]);
                int newRes = Math.abs(a[i] - b[leftBound]);
                if(newRes != 0){
                    if( res != -1){
                        res = Math.min(newRes,res);
                    }else{
                        res = newRes;
                    }
                } else{
                    return res = 0;
                }
            } else if(b[b.length / 2] < a[i]){
                int rightBound = rightSearch(b,a[i]);
                int newRes = Math.abs(a[i] - b[rightBound]);
                if(newRes != 0){
                    if( res != -1){
                        res = Math.min(newRes,res);
                    }else{
                        res = newRes;
                    }
                } else{
                    return res = 0;
                }
            } else{
                return res = 0;
            }
        }
        System.out.println(res);
        return res;
    }

    public int leftSearch(int[] arr,int target){
        int left = 0;
        int right = arr.length - 1;
        while(left <= right){
            int mid = left + (right - left)/2;
            if(arr[mid] > target){
                right = mid - 1;
            } else if( arr[mid] < target){
                if(target  - arr[mid]  > arr[mid + 1] - target){
                    return mid + 1;
                }
                return mid;
            } else{
                return mid;
            }
        }
        return left;
    }


    public int rightSearch(int[] arr,int target){
        int left = 0;
        int right = arr.length - 1;
        while(left <= right){
            int mid = left + (right - left) / 2;
            if(arr[mid] < target){
                left = mid + 1;
            } else if(arr[mid] > target ){
                if( arr[mid] - target >  target - arr[mid - 1]){
                  return mid - 1;
                }
               return mid;
            } else{
                return mid;
            }
        }
        return right;
    }
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页