一、题目来源及说明
题目来源:https://leetcode-cn.com/problems/two-sum/
题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
1
2
3
4
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
二、算法解析说明
算法一、暴力破解
1
2
3
4
5
6
7
8
9
10
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
}
算法中,用两个for循环遍历nums,将所有数字进行计算,得到的结果对比target,满足条件就返回位置,不满足返回nil。因为每次外循环都要遍历一次内循环,所以时间复杂度为O(n^2)。
算法二、一次遍历保存每次的计算结果
1
2
3
4
5
6
7
8
9
10
func twoSum(nums []int, target int) []int {
hashmap := make(map[int]int)
for i, sub := range nums {
if idx, ok := hashmap[target-sub]; ok {
return []int{idx, i}
}
hashmap[sub] = i
}
return nil
}
这个算法只有一次for遍历,所以时间复杂度为O(n)。算法首先建立hashmap数组,用来保存差为位置。它的作用就是保存每个nums值的位置,格式为hashmap[num] = index
。在遍历时,计算target和当前nums值,如果差在hashmap里面找到了,也就是当前的差在nums数组前面,此时当前的nums值的位置和前面nums值(差)的位置就是我们需要的结果了。
三、 额外说明
官方还有一个两次遍历的算法,其实就是先把nums里面的值遍历保存为hashmap[nums] = index
格式,然后再次遍历nums到hashmap里面查找有没有差。