From 6701af4f89bcd64476083e9fb3b5a16f00d584fa Mon Sep 17 00:00:00 2001 From: LouisFonda Date: Mon, 14 Apr 2025 18:15:22 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=B8=A4=E6=95=B0=E4=B9=8B=E5=92=8Cgo?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../leetcode-go/array/easy_two_sum.go | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 go_solutions/leetcode-go/array/easy_two_sum.go diff --git a/go_solutions/leetcode-go/array/easy_two_sum.go b/go_solutions/leetcode-go/array/easy_two_sum.go new file mode 100644 index 0000000..f7d0a2a --- /dev/null +++ b/go_solutions/leetcode-go/array/easy_two_sum.go @@ -0,0 +1,30 @@ +package main + +/* +使用哈希表 +*/ +func twoSum(nums []int, target int) []int { + hashTable := map[int]int{} + for i, x := range nums { + if val, ok := hashTable[target-x]; ok { + return []int{val, i} + } + hashTable[x] = i + } + return nil +} + +/* +暴力枚举,首先遍历整个数组,之后再遍历后边的所有元素,如果两个元素相加的值为target,就返回这两个 +下标 +*/ +func f1(nums []int, target int) []int { + for i, x := range nums { + for j := i + 1; j < len(nums); j++ { + if x+nums[j] == target { + return []int{i, j} + } + } + } + return nil +}