题目描述:
https://leetcode-cn.com/problems/3sum/
题解:
参考https://www.jianshu.com/p/eb18ba9dabf1
将nums从小到大排列,遍历nums数组,对每个元素nums[i]执行以下操作:
<1>设定两个指针j=i+1 k=len(nums)-1
<2>计算nums[i] nums[j] nums[k]之和,若为0,则加入tmp,若在result中为出现过,则将tmp写入res,j+1或k-1(不可同时改变)
<3>若不为0,大于0则k-1,小于0则j+1
def threeSum(self, nums): lennums = len(nums) result = [] nums.sort() for i in range(lennums-2): j = i+1 k = lennums-1 while j<k: sum = nums[i]+nums[j]+nums[k] if sum==0: tmp = [] tmp.append(nums[i]) tmp.append(nums[j]) tmp.append(nums[k]) j = j+1 k = k-1 if tmp not in result: result.append(tmp) if sum<0: j = j+1 else: k= k-1 return result