The Smallest Difference

    xiaoxiao2021-12-14  20

    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.

    Have you met this question in a real interview?  Yes Example

    For example, given array A = [3,6,7,4], B = [2,8,9,3], return 0

    来一道简单的题

    感觉最近遇到瓶颈了,不能够做到举一反三。感觉还是一些东西没有真正领会到。还需要不断地理解。

    这道题要找两个数组中的最小差距。提示给了复杂度nlogn, 自然想到排序。然后两个指针一次增长,求距离就可以了。

    代码:

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

    转载请注明原文地址: https://ju.6miu.com/read-963123.html

    最新回复(0)