如何优化两数之和配对代码 时间复杂度从O(n²)提升至O(nlogn)
两数之和整数对查找代码优化方案
原代码问题分析
你当前的代码已经预先对输入列表做了排序(排序操作本身时间复杂度为O(nlogn)),但后续嵌套双层循环遍历所有i<j的组合,这部分时间复杂度为O(n²),导致整体时间复杂度被拉到了O(n²),只需要把后续的遍历逻辑替换为双指针法即可完成优化。
优化思路
利用排序后数组的有序性,用双指针从两端向中间遍历,单次遍历即可找出所有符合要求的整数对:
- 保持原有的排序操作不变
- 初始化左指针
left指向数组起始位置(下标0),右指针right指向数组末尾位置(下标len(a)-1) - 循环判断直到
left >= right时终止:- 计算两个指针指向元素的和
current_sum = a[left] + a[right] - 若
current_sum == s:将(a[left], a[right])加入结果列表,同时左指针右移一位、右指针左移一位(因为输入列表元素唯一,无需处理重复值场景) - 若
current_sum < s:说明需要更大的加数才能达到目标和,将左指针右移一位 - 若
current_sum > s:说明需要更小的加数才能达到目标和,将右指针左移一位
- 计算两个指针指向元素的和
优化后代码
def pairs_of_sum(lst, s): """ Finds pairs of list elements with specific sum. Input : list of unique integers (lst), integer (s) Output: list containing all pairs (x, y) of elements of lst such that x < y and x + y = s For example: >>> pairs_of_sum([7, 1, 25, 10], 5) [] >>> pairs_of_sum([7, 1, 25, 10], 32) [(7, 25)] >>> pairs = pairs_of_sum([-2, 4, 0, 11, 7, 13], 11) >>> set(pairs) == {(0, 11), (4, 7), (-2, 13)} True """ a = sorted(lst) res = [] left = 0 right = len(a) - 1 while left < right: current_sum = a[left] + a[right] if current_sum == s: res.append((a[left], a[right])) left += 1 right -= 1 elif current_sum < s: left += 1 else: right -= 1 return res
复杂度验证
排序操作时间复杂度为O(nlogn),双指针遍历仅需扫描数组一次,时间复杂度为O(n),整体最坏时间复杂度为O(nlogn),符合要求。
内容的提问来源于stack exchange,提问作者Zayn
相关产品推荐
相关产品推荐

