题目:寻找三元组
分析:先排序,然后枚举第一个元素后寻找后两个。
python3 学习
List添加数据:
- list.append([a, b, c])
- list+= [[a, b, c]]
- list.extend([[a, b, c]])
性质1:单调的序列A中,寻找和为b的两个数,只需要O(n)O(n)O(n)。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
ans = []
sNum = len(nums)
for a in range(sNum):
if a and nums[a] == nums[a-1]:
continue
b = a+1
c = sNum-1
while b < c:
if b > a+1 and nums[b] == nums[b-1] or nums[a] + nums[b] + nums[c] < 0:
b += 1
elif nums[a] + nums[b] + nums[c] == 0:
ans.append([nums[a], nums[b], nums[c]])
b += 1
else:
c -= 1
return ans
本文深入探讨了寻找三元组算法,通过排序和双指针技巧,实现O(n^2)的时间复杂度。文章提供了Python代码示例,展示了如何在已排序的列表中寻找三个数相加等于特定目标值的有效方法。
1272

被折叠的 条评论
为什么被折叠?



