Title Link: http://www.lintcode.com/zh-cn/problem/the-smallest-difference/
Given an array of two integers (the first is an array A
, the second is an array B
), A[i] is taken in array A, and the difference between b[j],a[i] and B[j in array B is as small as possible (| A[i]-b[j]|). Returns the minimum difference.
After sequencing, scan two arrays with two pointers, each updating the absolute value of their difference. And according to the size of their two numbers to decide who will move the pointer.
1 classSolution:2 #@param A, b:two lists of integer3 #@return: An integer4 defsmallestdifference (self, A, B):5 #Write your code here6 A.sort ()7 B.sort ()8i =09j =0TenRET = 2147483647 One whileI < Len (A) andJ <Len (B): Aret = min (ret, ABS (a[i]-B[j])) - ifA[i] >B[j]: -J + = 1 the elifA[i] <B[j]: -i + = 1 - elifA[i] = =B[j]: -RET =0 + Break - returnRet
[Lintcode the-smallest-difference] min. difference (python)