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 +}