題目描述:算法
/*
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].
*/
這道題給了咱們一個數組,還有一個目標數target,讓咱們找到兩個數字,使其和爲target。首先想到的就是暴力搜索,遍歷全部的組合項,得到結果,思路比較簡單,代碼以下:
func func1(s []int, tag int) []int { for i := 0; i < len(s)-1; i++ { for j := i + 1; j < len(s); j++ { if s[i]+s[j] == tag { return []int{i, j} } } } return nil }
這個算法的時間複雜度是O(n^2)。雖然節省了空間,可是時間複雜度高。嘗試用空間換時間,使用一個HashMap,創建數字和其座標位置之間的映射,在遍歷數組的時候,用target減去遍歷到的數字,就是另外一個須要的數字了,直接在HashMap中查找其是否存在便可,那麼代碼就可這樣寫:
func func2(s []int, tag int) []int { hash := make(map[int]int) for i := 0; i < len(s); i++ { hash[s[i]] = i } for i := 0; i < len(s); i++ { temp := tag - s[i] if _, ok := hash[temp]; ok { if hash[temp] == i { continue } return []int{i, hash[temp]} } } return nil }
這個算法的時間複雜度是O(n)。再想一想,代碼好像能夠更加簡潔一些,把兩個for循環合併成一個:
func func3(s []int, tag int) []int { hash := make(map[int]int, len(s)) for k, v := range s { if j, ok := hash[tag-v]; ok { return []int{j, k} } hash[v] = k } return nil }
這樣看起來就比較舒服ok了,完整的貼上來,運行一下試試吧。
package main import ( "fmt" ) func main() { nums := []int{2, 7, 11, 15} target := 9 s := func1(nums, target) //s := func2(nums, target) //s := func3(nums, target) fmt.Printf("nums[%d]+nums[%d]=%d+%d=%d\n", s[0], s[1], nums[s[0]], nums[s[1]], target) fmt.Printf("return [%d,%d]", s[0], s[1]) } //暴力破解 時間複雜度O(n^2) func func1(s []int, tag int) []int { for i := 0; i < len(s)-1; i++ { for j := i + 1; j < len(s); j++ { if s[i]+s[j] == tag { return []int{i, j} } } } return nil } //用map輔助查找 時間複雜度O(n) func func2(s []int, tag int) []int { hash := make(map[int]int) for i := 0; i < len(s); i++ { hash[s[i]] = i } for i := 0; i < len(s); i++ { temp := tag - s[i] if _, ok := hash[temp]; ok { if hash[temp] == i { continue } return []int{i, hash[temp]} } } return nil } //優化一下,把兩個for循環合併成一個 func func3(s []int, tag int) []int { hash := make(map[int]int, len(s)) for k, v := range s { if j, ok := hash[tag-v]; ok { return []int{j, k} } hash[v] = k } return nil }