deftwoSum(): hashtable = dict() for i, num inenumerate(nums): if target - num in hashtable: return [hashtable[target - num], i] hashtable[nums[i]] = i return []
三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
# L 从 i+1 开始,R 从数组长度 -1 开始 L = i+1 R = n-1 while(L < R): if(nums[i]+nums[L]+nums[R] == 0): res.append([nums[i], nums[L], nums[R]]) while(L < R and nums[L] == nums[L+1]): L = L+1 while(L < R and nums[R] == nums[R-1]): R = R-1 L = L+1 R = R-1 elif(nums[i]+nums[L]+nums[R] > 0): R = R-1 else: L = L+1 return res