From 4068040965153cbcbdd970be6abf5fa31be517f0 Mon Sep 17 00:00:00 2001 From: ltinyho Date: Tue, 3 Aug 2021 14:43:44 +0800 Subject: [PATCH] =?UTF-8?q?0018.=E5=9B=9B=E6=95=B0=E4=B9=8B=E5=92=8C-golan?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0018.四数之和.md | 48 +++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index 0caf12be..4a8fa947 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -201,6 +201,54 @@ class Solution(object): ``` Go: +```go +func fourSum(nums []int, target int) [][]int { + if len(nums) < 4 { + return nil + } + sort.Ints(nums) + var res [][]int + for i := 0; i < len(nums)-3; i++ { + n1 := nums[i] + // if n1 > target { // 不能这样写,因为可能是负数 + // break + // } + if i > 0 && n1 == nums[i-1] { + continue + } + for j := i + 1; j < len(nums)-2; j++ { + n2 := nums[j] + if j > i+1 && n2 == nums[j-1] { + continue + } + l := j + 1 + r := len(nums) - 1 + for l < r { + n3 := nums[l] + n4 := nums[r] + sum := n1 + n2 + n3 + n4 + if sum < target { + l++ + } else if sum > target { + r-- + } else { + res = append(res, []int{n1, n2, n3, n4}) + for l < r && n3 == nums[l+1] { // 去重 + l++ + } + for l < r && n4 == nums[r-1] { // 去重 + r-- + } + // 找到答案时,双指针同时靠近 + r-- + l++ + } + } + } + } + return res +} +``` javaScript: