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++;

     

  • 相关阅读:
    css选择器
    HTML标签用法
    pyenv python 版本控制
    Django之路
    Day15-Django
    python+selenium实现登录账户
    requests and BeautifulSoup
    清除MAC 可清除空间
    将python源文件打包成exe文件
    swift的一些东西
  • 原文地址:https://www.cnblogs.com/apanda009/p/7261557.html
Copyright © 2011-2022 走看看