Two Sum With A Map Index

Index values as you scan, then look up the complement target-minus-current so each pair is found in one pass with no nested loops.

GoData Integrity

Code

gosnippet
21 lines
package main

import "fmt"

// twoSum 用 map 当倒排 index:返回和为 target 的两个下标,没有则返回 nil
func twoSum(nums []int, target int) []int {
	seen := make(map[int]int, len(nums))
	for i, v := range nums {
		if j, ok := seen[target-v]; ok {
			return []int{j, i}
		}
		seen[v] = i
	}
	return nil
}

func main() {
	nums := []int{2, 7, 11, 15}
	fmt.Println("pair:", twoSum(nums, 9))
	fmt.Println("none:", twoSum(nums, 30))
}

Inside the snippet

Two Sum With A Map Index keeps everything in the functions twoSum and main.

The cycling part of this snippet is for i, v := range nums.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: func twoSum(nums []int, target int) []int

The file announces its steps in the output: pair:, none:.

main calls 1 helper in sequence: twoSum.

Code under the headings

func twoSum(nums []int, target int) []int {
	seen := make(map[int]int, len(nums))
	for i, v := range nums {
		if j, ok := seen[target-v]; ok {
			return []int{j, i}
		}
		seen[v] = i
	}
	return nil
}
func main() {
	nums := []int{2, 7, 11, 15}
	fmt.Println("pair:", twoSum(nums, 9))
	fmt.Println("none:", twoSum(nums, 30))
}

Interactive Tools for This Topic

FAQ

What does Two Sum With A Map Index print when run?
Running the file directly is enough — expect labeled output lines such as `pair:`, `none:`.