Leetcode1. 两数之和(golang)

一、题目

题目来源:https://leetcode-cn.com/problems/two-sum

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

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

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

  • 示例 1:

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

  • 示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]

  • 示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

  • 提示:

2 <= nums.length <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案

二、题解

1. 暴力法

  • 思想:

暴力法顾名思义采用枚举的方式,挨个寻找nums中相加为target的数,找到后返回两数下标,这里采用双层循环的方式。

暴力法最差的情况列表需要循环n*n次,并没有耗费额外空间,因此:

  • 时间复杂度为:
    0 ( n 2 ) 0(n^2) 0(n2)
  • 空间复杂度为:
    0 ( 1 ) 0(1) 0(1)
  • 代码
 func twoSum(nums []int, target int) []int {
    
    
    //定义数组arr,用来返回结果下标
    arr := []int{
    
    }
    //双层循环,找到相加为target的两值下标
    for i := 0; i < len(nums); i++{
    
    
        for j := i + 1; j < len(nums); j++{
    
    
                if nums[i] + nums[j] == target{
    
    
                    //找到后添加到arr数组的尾部
                    arr = append(arr,i,j)
                }
        }
    }
    //返回arr
    return arr
}

2. hashmap

  • 思想:

暴力法时间消耗较长,因此可以使用hashmap的方法,将数值存于hashmap的键中,下标存于值中。循环遍历数组,将访问过的值存入hashmap中,如果target-v的值存在于hashmap中,那么我们就返回v的下标和hashmap[target-v]的下标。

查找hashmap中的值时间复杂度为0(1),一共有n个值,最坏情况要查n次。空间上开辟了hashmap,存放n个值,因此:

  • 时间复杂度为:
    0 ( n ) 0(n) 0(n)
  • 空间复杂度为:
    0 ( n ) 0(n) 0(n)
  • 代码
 func twoSum(nums []int, target int) []int {
    
    
    //定义hashmap,键为数值,值为下标
    hashmap := map[int]int{
    
    }
    //遍历nums数组
	for i,v := range nums{
    
    
        //如果存在值为target-v的数,就将其坐标赋给p
        //并返回p,i两下标
		if p,ok := hashmap[target-v];ok {
    
    
			return []int{
    
    p,i}
		}
        //若不存在就将该值和下标放入哈希表
		hashmap[v] = i
	}
	return nil

}

猜你喜欢

转载自blog.csdn.net/QQ395879676/article/details/115448701
今日推荐