zoukankan      html  css  js  c++  java
  • [lintcode the-smallest-difference]最小差(python)

    题目链接:http://www.lintcode.com/zh-cn/problem/the-smallest-difference/

    给定两个整数数组(第一个是数组 A,第二个是数组 B),在数组 A 中取 A[i],数组 B 中取 B[j],A[i] 和 B[j]两者的差越小越好(|A[i] - B[j]|)。返回最小差。

    排好序后用两个指针分别扫描两个数组,每次更新他们的差值的绝对值。并且依据他们两个数字的大小来决定谁来移动指针。

     1 class Solution:
     2     # @param A, B: Two lists of integer
     3     # @return: An integer
     4     def smallestDifference(self, A, B):
     5         # write your code here
     6         A.sort()
     7         B.sort()
     8         i = 0
     9         j = 0
    10         ret = 2147483647
    11         while i < len(A) and j < len(B):
    12             ret = min(ret, abs(A[i]-B[j]))
    13             if A[i] > B[j]:
    14                 j += 1
    15             elif A[i] < B[j]:
    16                 i += 1
    17             elif A[i] == B[j]:
    18                 ret = 0
    19                 break
    20         return ret
  • 相关阅读:
    【简】题解 AWSL090429 【市场】
    【简】题解 AWSL090429 【噪音】
    差分约束
    凸包模板
    杂模板
    后缀数组刷题
    Trie刷题
    字符串模板
    网络流建模专题
    组合数模板
  • 原文地址:https://www.cnblogs.com/kirai/p/5597150.html
Copyright © 2011-2022 走看看