经典算法面试题系列 (二)——three sum

接着two sum,three sum的难度上升了不少。因为two sum的答案是唯一的,three sum的答案是多个。题目链接https://leetcode.com/problems/3sum/#/description。

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]
]
其实还是像two sum,先假设已经找到第一个数,剩下的就是循环判断第二个数加上第三个数等于第一个数。当然还有一个问题,就是需要处理重复。处理重复思路是这样的,先找到所有的组合,再做处理。

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);


你可能感兴趣的:(算法)