0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

leetcode刷题日记之两数之和

Posted at

审题

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

思路

给了一个数组和一个目标值,要求找到数组中两个数值相加等于目标值的索引。

方法一可以直接穷举遍历

func twoSum(nums []int, target int) []int {
    for index,num := range nums{
        for j:=index+1;j<len(nums);j++{
            if num+nums[j] == target{
                return []int{index,j}
            }
        }
    }
    return []int{0,0}
}

j:=index+1是期望第二组for循环从下标为1开始,而非0开始,避免数组中同一个元素在答案里重复出现

方法二用到哈希表,将数组每个数的值与目标值做差值存入map,拿到一个数就用目标值减去这个数值,看数组值是不是map中的其中一个差值,降低复杂度。

func twoSum(nums []int, target int) []int {
    mapSum := map[int]int{}
    for i,v := range nums{
        if idx,exist := mapSum[v];exist{
            return []int{idx,i}
        }
        mapSum[target-v]=i
    }
    return []int{0,0}
}

或者将数值放入map当作key,数值的索引当作map的value,然后判断差值在不在map中

func twoSum(nums []int, target int) []int {
    m := map[int]int{}
    for i, v := range nums {
        find := target - v
        if _, e := m[find]; e {
            return []int{m[find], i}
        }
        m[v] = i
    }
    return []int{}
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?