L15_3sum

题目描述

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],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

解题思路

首先将数组进行排序,排序后使用3个索引进行sum的判断

Go版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import (
"sort"
)

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--
}else if 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
}

Python版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution(object):
def (self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
r = []

nums = sorted(nums)
l = len(nums)

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 not in r:
r.append(t)
j += 1
k -= 1
return r