最小差
给定两个整数数组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