From cd03a5b79a5deb90e444d46ba4c22cffd9478440 Mon Sep 17 00:00:00 2001 From: markwang Date: Tue, 7 May 2024 10:57:05 +0800 Subject: [PATCH] =?UTF-8?q?15.=E4=B8=89=E6=95=B0=E4=B9=8B=E5=92=8C?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0Go=E5=93=88=E5=B8=8C=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0015.三数之和.md | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index ae218385..f7146907 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -403,6 +403,7 @@ class Solution: ``` ### Go: +(版本一) 双指针 ```Go func threeSum(nums []int) [][]int { @@ -442,6 +443,42 @@ func threeSum(nums []int) [][]int { return res } ``` +(版本二) 哈希解法 + +```Go +func threeSum(nums []int) [][]int { + res := make([][]int, 0) + sort.Ints(nums) + // 找出a + b + c = 0 + // a = nums[i], b = nums[j], c = -(a + b) + for i := 0; i < len(nums); i++ { + // 排序之后如果第一个元素已经大于零,那么不可能凑成三元组 + if nums[i] > 0 { + break + } + // 三元组元素a去重 + if i > 0 && nums[i] == nums[i-1] { + continue + } + set := make(map[int]struct{}) + for j := i + 1; j < len(nums); j++ { + // 三元组元素b去重 + if j > i + 2 && nums[j] == nums[j-1] && nums[j-1] == nums[j-2] { + continue + } + c := -nums[i] - nums[j] + if _, ok := set[c]; ok { + res = append(res, []int{nums[i], nums[j], c}) + // 三元组元素c去重 + delete(set, c) + } else { + set[nums[j]] = struct{}{} + } + } + } + return res +} +``` ### JavaScript: