01.两数之和

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

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

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

 python3

# 解法一:暴力解法
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        result = []
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if target == nums[i] + nums[j]:
                    result.append(i)
                    result.append(j)
        return result
      
  
# 解法二:哈希map
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        result = {}
        for index, value in enumerate(nums):
            if result.get(target-value) is not None:
                return [index, result.get(target-value)]
            result[value] = index
        return result
        
# 注:enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

Go

解法一:
func twoSum(nums []int, target int) []int {
    for i := 0;i<len(nums);i++ {
        for j:=i+1;j<len(nums);j++ {
            if target == nums[i] + nums[j] {
                return []int{i,j}
            }
        }
    }
    return nil
}
时间复杂度:O(N^2)

解法二:
func twoSum(nums []int, target int) []int {
    hashmap := map[int]int{}
    for index, value := range nums {
        if p, ok := hashmap[target-value]; ok {
            return []int{index,p}
        }
        hashmap[value] = index
    }
    return nil
}

知识点:

map:map[k]T,“K”意为键的类型,而“T”则代表元素(或称值)的类型。如果我们要描述一个键类型为int、值类型为string的字典类型的话:map[int]string

数组:[]type{..}

map 判断 key 是否存在?

if _, ok := map[key]; ok {
    //存在
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值