<?phpclass Solution { /** * nums = [-1, 2, 1, -4] * target = 1 * closest = 2 * @param $nums * @param $target * @return array|mixed */ public function threeSumClosest($nums, $target) { if (!$nums) return []; sort($nums); $closest = $nums[0] + $nums[1] + $nums[2]; for ($i = 0; $i < count($nums) - 2; $i++) { // 前后指针 $left = $i + 1; $right = count($nums) - 1; while ($left < $right) { $sum = $nums[$i] + $nums[$left] + $nums[$right]; if ($sum > $closest) { $right--; } else { $left++; } if (abs($sum - $target) < abs($closest - $target)) { $closest = $sum; } } } return $closest; }}$nums = [-1, 2, 1, -4];$cls = new Solution();$r = $cls->threeSumClosest($nums, 1);print_r($r);