题目:3Sum
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.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
解题思路:
先选定一个数字a,则将问题转化为寻找两个数之和为-a的问题,故可以先将列表排序,然后从两端的数字开始求和,根据结果将符合要求的记下,并移动下标再作求和。时间复杂度为O(N*N)
代码:
class Solution: def threeSum(self, nums): nums = sorted(nums) result = [] for i in range(len(nums)): if i!= 0 and nums[i] == nums[i-1]: continue front = i + 1 back = len(nums) - 1 while(front < back): if nums[i] + nums[front] + nums[back] < 0: front += 1 elif nums[i] + nums[front] + nums[back] > 0: back -= 1 else: new_list = [nums[i], nums[front], nums[back]] result.append(new_list[:]) f = front b = back while front < back and nums[front] == nums[f]: front+= 1 while front < back and nums[back] == nums[b]: back -= 1 return result