玖叶教程网

前端编程开发入门

Leetcode力扣算法题目——三数之和

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

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

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

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

PHP代码实现

class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer[][]
     */
    function threeSum($nums) {
        sort($nums);
        $len = count($nums);
        $res = [];
        for($i = 0; $i < $len -2; $i ++) {
            $l = $i + 1;
            $r = $len - 1;
            while ($l < $r) {
                $sum = $nums[$i] + $nums[$l] + $nums[$r];
                if ($sum === 0 && $r > $l) {
                    $tmp   = [$nums[$i], $nums[$l], $nums[$r]];
                    $res[] = $tmp;
                    while ($l < $r && $nums[$r] === $nums[$r - 1]) {
                        $r--;
                    }
                    while ($l < $r && $nums[$l] === $nums[$l + 1]) {
                        $l++;
                    }
                    $r--;
                    $l++;
                } else {
                    if ($sum > 0) {
                        $r--;
                    } else {
                        $l++;
                    }
                }

            }
        }
        return array_unique($res, SORT_REGULAR);
    }
}

结果

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言