每周完成一个 ARTS: Algorithm: 每周至少做一个 LeetCode 的算法题 Review: 阅读并点评至少一篇英文技术文章 Tips: 学习至少一个技术技巧 Share: 分享一篇有观点和思考的技术文章
Algorithm
1. 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解析
twoSum.go
package leetCode
/*
** 解析:
** 假设两个元素分别为 a, b
** a + b = target => b = target - a
** 使用 map 将数组元素存储起来,步骤如下:
** a = range nums
** b = target - a
** if map[b] != true 则 map[b] = a的下标
** else return a的下标,map[b]的值
*/
func GetTwoSumIndex( nums []int, target int) []int {
// 存储数组元素,用于获取 b 的下标
indexs := make(map[int]int, len(nums))
for i, a := range nums {
// 获取 b 值的下标
if j, ok := indexs[target - a]; ok {
return []int{i, j}
}
// 将数组元素逐一存储在 map 中,用于获取 b 值的下标
indexs[a] = i
}
return nil
}
twoSum_test.go
package leetCode
import (
"testing"
)
func TestGetTwoSumIndex(t *testing.T) {
nums := []int{3, 4, 5, 7, 9}
target := 12
if indexs := GetTwoSumIndex(nums, target); indexs != nil {
t.Logf("find the index [%d], [%d]", indexs[0], indexs[1])
} else {
t.Logf("the indexs not exist")
}
}
Review
Tips
Share
最近在看并发方面的东西,推荐一个入门的博客教程《Linux系统高级编程系列教程》,再推荐一本书《C++ concurrency in action》
Summary
第一周有点粗糙,相信会慢慢写出更好的东西。。。