力扣-简单-两数之和

题目

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

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        records = dict()
        for index,value in enumerate(nums):
            if target - value not in records:  //查找值
                records[value]=index  //保存当前元素的值和下标

            else:
                return [records[target - value],index]

基础知识

1. dict() 函数用于创建一个字典。

形式:{'key':'value'}

存储:dictionary[key] = item

如:

n = dict({'x': 1, 'y': 2})
print('n =',n)

n = {'x': 1, 'y': 2}

2.循环并获取元素下标

使用enumerate(枚举)函数:用于将一个可遍历的数据对象组合为一个索引序列,同时列出数据和数据下标。

index:下标      value:值

for index, value in enumerate(num):
print(index, value)

3.in 和 not in

in:用于判断是否存在于字典中,如果在字典 dict 里返回 true,否则返回 false。

not in:如果在字典 dict 里返回 false,否则返回 true。

题目中,value为键,下标为值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值