例如,切片[12,16,34,4,9,6,21],target=38,求切片对应的下标?
package main
import "fmt"
func twoSum(nums []int, target int) []int {
recordMap := make(map[int]int)
resultArray := make([]int, 0)
for k, v := range nums {
if _, s := recordMap[target-v]; s {
resultArray = append(resultArray, recordMap[target-v])
resultArray = append(resultArray, k)
}
recordMap[v] = k
}
return resultArray
}
func main() {
num := []int{12,16,34,4,9,6,21}
fmt.Println(twoSum(num, 38))
}
[2 3]
大概的思路是:
target不断的和切片中的每个元素相减,然后再去匹配相减后的结果是否在切片中。时间复杂度为O(n)