Two Sum

来源:互联网 发布:多因子选股 知乎 编辑:程序博客网 时间:2024/05/29 03:26

问题

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.



测试用例

Given nums = [2, 7, 11, 15], target = 9,


Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].


我的代码

func twoSum(nums []int, target int) []int {    return_slice := make([]int, 2)        for i := 0; i < len(nums); i++  {        if i == len(nums) - 1 {            break        }        for j := i+1; j < len(nums); j++ {            if nums[i] + nums[j] == target{                fmt.Println(i, j)                return_slice[0] = i                return_slice[1] = j            }        }    }    return return_slice}