LeetCode

1 两数之和

package main

import "fmt"

func twoSum(target int) []int {
    var nums = []int{2, 7, 11, 3, 6, 5, 415}
    //使用哈希表,降低时间复杂度
    ns := make(map[int]int)
    for i := 0; i < len(nums); i++ {
        //遍历数组,用target减去nums[i],如果这个数存在hash中,那么就存在,hash认为是O(1)的时间复杂度
        another := target - nums[i]
        if y, ok := ns[another]; ok {
            return []int{y, i}
        }
        //将数:索引存入hash表
        ns[nums[i]] = i

    }
    return []int{}

}

func main() {
    fmt.Println(twoSum(9))
}

回复

This is just a placeholder img.