Given an array S of n integers, are there elements a, b, c in S 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.
1 2 3 4 5 6 7
For example, given array S = [-1, 0, 1, 2, -1, -4],
func(nums []int) [][]int { l := len(nums) r := [][]int{} sort.Ints(nums) for i:=0; i<l-2;i++ { j := i+1 k := l-1
for j<k { s := nums[i] + nums[j] + nums[k]
if s>0{ k-- }elseif s<0 { j++ }else { row:=[]int{nums[i],nums[j], nums[k]} flag := true for _, v := range r{ if v[0]==row[0] &&v[1] == row[1] && v[2] == row[2] { flag = false break } } if flag { r = append(r,row) } j++ k-- } } } return r }
for i in range(l): j = i + 1 k = l - 1 while j < k: s = nums[i] + nums[j] + nums[k] if s > 0: k -= 1 elif s < 0: j += 1 else: t = [nums[i], nums[j], nums[k]] if t notin r: r.append(t) j += 1 k -= 1 return r
近期评论