[LeetCode By Go 103]1. Two Sum

题目

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].

解题思路

方案一

两层循环,遍历所有可能性,找到目标解

func twoSum(nums []int, target int) (ret []int) {
    numLen := len(nums)
    for i := 0; i < numLen-1; i++ {
        // fmt.Printf("%d: %d\n", i, nums[i])
        for j := i + 1; j < numLen; j++ {
            sum := nums[i] + nums[j]
            // fmt.Printf("sum:%d = %d + %d\n", sum, nums[i], nums[j])

            if target == sum {
                ret = []int{i, j}
            }
        }
    }
    return ret
}

方案二

将数组中的值val和位置pos对应的键值对放入map中,通过hash表查找使val2 = target – val 的值,如果找到则返回结果,找不到,则将当前值插入map

注意
如果先把所有值都放入map中,如果目标结果是两个相同值相加得到的,则不能找到目标结果,比如

nums = []int{3,3}, target = 6

func twoSum(nums []int, target int) []int {
    var numMap map[int]int
    numMap = make(map[int]int)
    var ret []int

    for index, val := range nums {
        val2 := target - val
        fmt.Printf("val:%+v, index:%+v, val2:%+v\n", val, index, val2)

        index2, ok := numMap[val2]
        if ok && index != index2 {
            ret = []int{index, index2}
            break
        }

        numMap[val] = index
    }

    fmt.Printf("numMap:%+v\n", numMap)

    return ret
}

测试

twoSum_test.go

package _1_Two_Sum

import "testing"

func TestTwoSum(t *testing.T) {
    var tests = []struct{
        input []int
        target int
        output []int
    }{
        {[]int{3, 2, 4}, 6, []int{1, 2}},
        {[]int{3, 3}, 6, []int{0, 1}},
    }

    for _, v := range tests {
        ret := TwoSum(v.input, v.target)

        if ret[0] == v.output[0] && ret[1] == v.output[1] {
            t.Logf("pass")
        } else if ret[0] == v.output[1] && ret[1] == v.output[0] {
            t.Logf("pass")
        } else {
            t.Errorf("fail, want %+v, get %+v", v.output, ret)
        }
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/57e8b692ad97
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞