001-Two Sum 两数之和

Description:Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

给一个整数数组,和一个目标值,查询数组中两个数之和为目标值的数据位置。

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution:

 //使用空间换时间,查询之后放入map中,可以减少时间复杂度
func TwoSumMap1(nums []int,target int)[]int   {
    maps := map[int]int{}
    for i ,value := range  nums {
        member := target - value
        if j,ok := maps[member];ok  {
            return []int{j,i}
        }
        maps[value] = i
    }
    return nil
}

//双重遍历数组,拿数组中元素进行运算
 //耗时较多
 func twoSum(nums []int, target int) []int {
    for i := 0; i < len(nums);i ++ {
        for j := i +1; j < len(nums); j ++{
            if nums[i] + nums[j] == target {
                return []int{i,j}
            }
        }
    }
    return nil
 }