github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/algorithm/leetcode/two-sum_test.go (about)

     1  package leetcode
     2  
     3  //1. 两数之和 https://leetcode-cn.com/problems/two-sum/submissions/
     4  
     5  func twoSum(nums []int, target int) []int {
     6  	length := len(nums)
     7  	res := make([]int, 2)
     8  	tmpMap := make(map[int]int)
     9  
    10  	var t int
    11  	for i := 0; i < length; i++ {
    12  		t = target - nums[i]
    13  		if v, ok := tmpMap[t]; ok {
    14  			res[0] = i
    15  			res[1] = v
    16  			return res
    17  		}
    18  		tmpMap[nums[i]] = i
    19  	}
    20  	panic("没有找到")
    21  }