LeetCode 15. 三数之和

LeetCode 15. 三数之和

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]


php 代码

function threeSum($nums) {
    sort($nums);
    $ans = array();
    for ($i = 0; $i < count($nums) - 2; ++ $i) {
        if ($nums[$i] > 0 and ($i != 0 and $ans[$i] == $ans[$i - 1])) break; // 剪枝,去重
        $j = $i + 1;
        $k = count($nums) - 1;
        while ($j < $k) {
            $sum = $nums[$i] + $nums[$j] + $nums[$k];
            if ($sum == 0) {
                array_push($ans, array($nums[$i], $nums[$j], $nums[$k]));
                while ($j < $k and $nums[$j] == $nums[$j + 1]) ++ $j; // 去重
                while ($j < $k and $nums[$k] == $nums[$k - 1]) -- $k; // 去重
                ++ $j;
                -- $k;
            }
            elseif ($sum < 0) ++ $j;
            else -- $k;
        }
    }
    return array_unique($ans, 3);
}
 
原文地址:https://www.cnblogs.com/GetcharZp/p/11790078.html