zoukankan      html  css  js  c++  java
  • The Smallest Difference

    Given two array of integers(the first array is array A, the second array is array B), 
    now we are going to find a element in array A which is A[i], and another element in array B which is B[j],
    so that the difference between A[i] and B[j] (|A[i] - B[j]|) is as small as possible,
    return their smallest difference.

    两个数组两个指针

    两个数组的题常sort, 再通过两指针遍历

    public int smallestDifference(int[] A, int[] B) {
            // write your code here
            if (A == null || B == null || A.length == 0 || B.length == 0) {
                return -1;
            }
            Arrays.sort(A);
            Arrays.sort(B);
            int i = 0, j = 0;
            int ans = Integer.MAX_VALUE;
            while (i < A.length && j < B.length) {
                if (ans == 0) {
                    return ans;
                } else {
                    ans = Math.min(ans, Math.abs(A[i] - B[j]));
                }
                if (A[i] < B[j]) {
                    i++;
                } else {
                    j++;
                }
                
            }
            return ans;
            
        }
    

     常常与0 的差的正负来判断,  来判断指针的走位, 此处直接判断大小更方便

     if (A[i] < B[j]) {
                    i++;

     

  • 相关阅读:
    Python之图片格式转换
    pip依赖安装与记录
    Spectral Graph Theory的一些定理
    Beamer加中文
    Python之json
    Windows之建立C++开发环境
    Mysql分表教程
    null和空 not null
    yii 隐藏index.php的步骤
    yii泛域名
  • 原文地址:https://www.cnblogs.com/apanda009/p/7261557.html
Copyright © 2011-2022 走看看