算法面试题:最小差、单词距离(双指针,求最小差距离问题)

最小差

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

示例:
输入:{1, 3, 15, 11, 2}, {23, 127, 235, 19, 8}
输出:3,即数值对(11, 8)

提示:
1 <= a.length, b.length <= 100000
-2147483648 <= a[i], b[i] <= 2147483647
正确结果在区间 [0, 2147483647] 内

解题思路:排序+双指针
class Solution:
    def smallestDifference(self, a: List[int], b: List[int]) -> int:
        a.sort()
        b.sort()
        res=float('inf')
        n=len(a)
        m=len(b)
        i,j=0,0
        while i<n and j<m:
            if a[i]>b[j]:
                res=min(res,a[i]-b[j])
                j+=1
            elif a[i]<b[j]:
                res=min(res,b[j]-a[i])
                i+=1
            else:
                return 0
        return res

面试题 17.11. 单词距离

有个内含单词的超大文本文件,给定任意两个单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗?

示例:
输入:words = [“I”,“am”,“a”,“student”,“from”,“a”,“university”,“in”,“a”,“city”], word1 = “a”, word2 = “student”
输出:1

提示:
words.length <= 100000

双指针
class Solution:
    def findClosest(self, words: List[str], word1: str, word2: str) -> int:
        idx1, idx2 = float("-inf"), float("inf")
        res = len(words)
        for idx, word in enumerate(words):
            if word == word1:
                idx1 = idx
            elif word == word2:
                idx2 = idx
            res = min(res, abs(idx1-idx2))
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值