From 9219242b3af749a96efbbaf7d8ea5089a36ba7fe Mon Sep 17 00:00:00 2001 From: NevS <1173325467@qq.com> Date: Tue, 1 Jun 2021 20:34:57 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200001.=E4=B8=A4=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8C=20go=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用map方式解题,降低时间复杂度 --- problems/0001.两数之和.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 77318294..3d0674ce 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -134,6 +134,20 @@ func twoSum(nums []int, target int) []int { } return []int{} } + +```go +// 使用map方式解题,降低时间复杂度 +func twoSum(nums []int, target int) []int { + m := make(map[int]int) + for index, val := range nums { + if preIndex, ok := m[target-val]; ok { + return []int{preIndex, index} + } else { + m[val] = index + } + } + return []int{} +} ``` Rust