观察代码差异,看看如何降低复杂度和内存。

最重要的是追求时间复杂度和空间复杂度最好,而不是追求代码编写方式导致的差异
以下是两数之和,思想均是判断数组中的值与target的差是否在map中,如果不在就添加至map,在的话就返回。但是两种不同的编写方式却会导致执行用时有差异。

func twoSum(nums []int, target int) []int {
	dMap := make(map[int]int)
	for idx,val := range nums{
		minus := target-val
		if _,ok := dMap[minus];ok {
			return []int{dMap[minus],idx}
		}else {
			dMap[val]=idx
		}
	}
	return nil
}

执行用时:0 ms 内存消耗:3 MB

func twoSum(nums []int, target int) []int {
	var dMap = make(map[int]int)
	for idx, val := range nums {
		_, ok := dMap[target-val]
		if ok {
			return []int{idx, dMap[target-val]}
		} else {
			dMap[val] = idx
		}
	}
	return nil
}

执行用时:8 ms 内存消耗:3 MB