zoukankan      html  css  js  c++  java
  • 面试题 16.06. 最小差

    给定两个整数数组ab,计算具有最小差绝对值的一对数值(每个数组中取一个值),并返回该对数值的差

    示例:

    首先需要对两个数组进行排序;

    排序之后

    a = [1, 2, 3, 11, 15]

    b = [8, 19, 23, 127, 235]

    定义两个指针i和j分别用来扫a和b

    当a[i]和b[j]时获得了一个差值,此时需要判断连个列表中指针的移动方向:

    如果a[i] > b[j],那么需要移动j指针,否则差值只会变大

    如果a[i] < b[j],那么需要移动i指针,否则差值只会变大

    代码如下:

    class Solution:
        def smallestDifference(self, a: List[int], b: List[int]) -> int:
            a.sort()
            b.sort()
    
            i, j, res = 0, 0, 1 << 60
            while i < len(a) and j < len(b):
                res = min(res, abs(a[i] - b[j]))
                if a[i] > b[j]:
                    j = j + 1
                else:
                    i = i + 1
            
            return res
  • 相关阅读:
    使用Delphi调用条形码控件BarTender打印标签
    我看过的书
    语法规则
    智能家居
    HAL库ADC的DMA采集
    HAL库串口中断接收
    触动心灵的一句话
    摄影技巧
    中国茶道
    单片机延时函数
  • 原文地址:https://www.cnblogs.com/canaan233/p/13721261.html
Copyright © 2011-2022 走看看