twoSum的golang map方式实现

目标计算一个slice中求两个值的总和为固定值;

a + b = t
a = t - b

通过构建 map m[t-b] = i // i是下标的位置

在构建过程进行判断,如果存在m[a], 则返回 j的位置, // 这部通过hash的方式定位;

  • 计算复杂度是 O(N), 主要是 m[a]寻找的时候是hash O(1)的速度
  • 空间复杂度是 O(N), 重新构建了一个map;
func twoSum(nums []int, target int) []int {
    len := len(nums)
    a := make(map[int]int, len)

    for i := 0; i < len; i++ {
        j, ok := a[nums[i]]    // 这里对map中存在的值进行判断,如果
        if ok {
            return []int{j, i}
        } else {
            a[target-nums[i]] = i        // 这里构建map,
        }
    }
    return []int{0, 0}
}

猜你喜欢

转载自www.cnblogs.com/gpan/p/9859313.html