Golang学习之路 - LeetCode-Go-Learning 第一题. 两数之和

鸣谢: LeetCode-In-Go

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

解法 1 暴力解法

解题思路

主要思路:

  1. 遍历所有项
  2. 内层遍历从当前项后面开始,跟当前项相加,计算结果
  3. 遇到和target相等则返回

具体实现代码:

// 基本的暴力解法。
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
}

解法 2 查询差值序号

解题思路

a + b = target

也可以看成是

a = target - b

map[整数]整数的序号中,可以查询到a的序号。这样就不用嵌套两个for循环了。

// 使用map的解法
func twoSum(nums []int, target int) []int {
    index := make(map[int]int, len(nums))
    
    // 通过for循环获取b的序号 
    for i, b := range nums {
        // 通过查询序号来获得 a = target - b 的序号
        if j, ok := index[target - b]; ok {
            // ok 为 true的时候,那么就是对应的a = target - b。
            return []int{j, i}
        }
        // 把 b 和 i的值,存入map
        index[b] = i
    }
    return nil
    
}

运行效率对比:
在这里插入图片描述

编写测试程序

package problem0001

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

type para struct {
	one []int
	two int
}

type ans struct {
	one []int
}

type question struct {
	p para
	a ans
}

func Test_OK(t *testing.T) {
	ast := assert.New(t)

	qs := []question{
		question{
			p: para{
				one: []int{3, 2, 4},
				two: 6,
			},
			a: ans{
				one: []int{1, 2},
			},
		},
		question{
			p: para{
				one: []int{3, 2, 4},
				two: 8,
			},
			a: ans{
				one: nil,
			},
		},
	}

	for _, q := range qs {
		a, p := q.a, q.p
		ast.Equal(a.one, twoSum(p.one, p.two), "输入:%v", p)
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值