Leetcode: 3 Sum

久违的刷一发 Leetcode。

3 Sum

PHP

class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer[][]
     */
    function threeSum($nums) {
        sort($nums);
        $count = count($nums);
        $result = [];
        for ($i = 0; $i < $count - 2; $i++) {
            $j = $i + 1;
            $k = $count - 1;
            while ($j < $k) {
                $sum = $nums[$i] + $nums[$j] + $nums[$k];
                if ($sum === 0) {
                    $result[$nums[$i].",".$nums[$j].",".$nums[$k]] = [$nums[$i], $nums[$j], $nums[$k]];
                    $j++;
                    $k--;
                } elseif ($sum < 0) {
                    $j++;
                } else {
                    $k--;
                }
            }
        }
        return $result;
    }
}

 424 total views