# 经典算法面试题系列 （二）——three sum

Given an array S of n integers, are there elements abc 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.

``````For example, given array S = [-1, 0, 1, 2, -1, -4],

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

1.golang 版

``````package main

import (
"fmt"
"sort"
)

func main() {
var nums = []int{-1, 0, 1, 2, -1, -4}
three := threeSum(nums)
fmt.Println(three)
}

func threeSum(nums []int) [][]int {
if len(nums) <= 0 {
return [][]int{}
}

if !sort.IntsAreSorted(nums) {
sort.Ints(nums)
}

var sum int
var res [][]int
for i := 0; i < len(nums); i++ {
target := -nums[i]
front := i + 1
back := len(nums) - 1

for front < back {
sum = nums[front] + nums[back]

if sum < target {
front++
} else if sum > target {
back--
} else {
var tripliet = []int{nums[i], nums[front], nums[back]}
res = append(res, tripliet)

for front < back && nums[front] == tripliet[1] {
front++
}
for front < back && nums[back] == tripliet[2] {
back--
}
}
}

for i+1 < len(nums) && nums[i+1] == nums[i] {
i++
}
}

return res
}
``````

2.php 版

``````function threeSum(\$nums) {
if (count(\$nums) <= 0) {
return [[]];
}

sort(\$nums);
\$res = [];
for(\$i = 0; \$i < count(\$nums); \$i++) {
\$target = -\$nums[\$i];
\$front = \$i + 1;
\$back = count(\$nums) - 1;

while(\$front < \$back) {
\$sum = \$nums[\$front] + \$nums[\$back];
if (\$sum < \$target) {
\$front ++;
} else if (\$sum > \$target) {
\$back --;
} else {
\$triplet = [\$nums[\$i], \$nums[\$front], \$nums[\$back]];
\$res[] = \$triplet;
while(\$front < \$back && \$nums[\$front] == \$triplet[1]) {
\$front ++;
}

while(\$front < \$back && \$nums[\$back] == \$triplet[2]) {
\$back --;
}
}
}

while(\$i + 1 < count(\$nums) && \$nums[\$i + 1] == \$nums[\$i]) {
\$i ++;
}
}

return \$res;
}

\$nums = [-1, 0, 1, 2, -1, -4];
\$three = threeSum(\$nums);
var_dump(\$three);``````