LeetCode题解-Go 0x0000

193 阅读1分钟

搭建单元测试框架

  1. 以two-sum为例,第一个输入参数是int数组,第二个输入参数是int,输出结果是int数组。在Go中定义如下结构对应本题的输入、输出数据。
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
// 输入参数
type para struct {
	one []int // 第一个参数
	two int // 第二个参数
}

// 输出结果
type ans struct {
	one []int // 输出结果
}

// 
type question struct {
	p para
	a ans
}
  1. 使用Go自带的单元测试,并引入assert库。
import (
	"testing"

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

func TestTwoSum(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)
	}
}

  1. 使用Vscode运行单元测试,结果如下。

图1.1 单元测试

图1.2 代码覆盖率