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.
Code
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
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.