Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
题目意思就是给出一串整型数字,求它们中3个数字之和为0的所有情况。
思路:从中心向两边扩展
一开始想的是从两边向中心扩展,后来发现会漏掉一些情况。然后考虑从中心向两边扩展的思路。遍历每个位置,以这个位置为中心,从左侧第一个以及右侧第一个位置开始,计算三个位置数字之和。如果小于0,则右侧数字向右移动;如果大于0,则左侧数字向左移动。同时要保存上一次移动的位置,以便在和为0的时候继续移动。也要考虑去重,所以这里使用map来保存结果,最后遍历保存到一个数组中输出。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
sortNums = sorted(nums)
print(sortNums)
l = len(sortNums)
ansMap={}
ans = []
# 从中心向两边扩展
center = 1
toRightFlag = True # True:right+=1 ; False:left-=1
for center in range(l-1):
left = center -1
right = center + 1
while left >= 0 and right < l:
tmpSum = sortNums[left]+sortNums[center]+sortNums[right]
if tmpSum == 0:
ansMap[str(sortNums[left])+","+str(sortNums[center])+","+str(sortNums[right])]=[sortNums[left],sortNums[center],sortNums[right]]
if toRightFlag:
right = right + 1
else:
left = left -1
if tmpSum < 0:
right = right + 1
toRightFlag = True
if tmpSum > 0:
left = left -1
toRightFlag = False
for key, value in ansMap.items():
ans.append(value)
return ans
THE END.
博客围绕LeetCode 15. 3Sum题展开,题目要求找出整型数字串中3个数字之和为0的所有情况。最初从两边向中心扩展思路会漏情况,后采用从中心向两边扩展思路,遍历各位置,计算三数和并根据大小移动左右数字,同时考虑去重,用map保存结果后输出。

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



