算法题---两数之和

package main

import "fmt"

/*
给出一个整数数组,请在数组中找出两个加起来等于目标值的数,
你给出的函数twoSum 需要返回这两个数字的下标(index1,index2),需要满足 index1 小于index2.。注意:下标是从1开始的
假设给出的数组中只存在唯一解
例如:
给出的数组为 {20, 70, 110, 150},目标值为90
输出 index1=1, index2=2

输入
[3,2,4],6
输出
[2,3]
*/


func twoSum(nums []int, target int) []int{
    tmpMap := make(map[int]int, len(nums))
    for index1 := range nums{
        want := target - nums[index1]
        if index2, ok := tmpMap[want]; ok{
            return []int{index2 + 1, index1 +1}
        }
        if _, ok := tmpMap[nums[index1]]; ok{
            continue
        }
        tmpMap[nums[index1]] = index1
    }
    return nil
}


func main(){
    nums := []int{3, 3, 4, 5}
    res := twoSum(nums, 7)
    fmt.Println(res)
}

 

posted @ 2021-04-15 10:16  威威后花园  阅读(56)  评论(0编辑  收藏  举报