Golang 基础
鸣谢: 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 暴力解法
解题思路
主要思路:
- 遍历所有项
- 内层遍历从当前项后面开始,跟当前项相加,计算结果
- 遇到和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)
}
}