python刷题笔记1--Two Sum
来源:互联网 发布:linux 重启机器 编辑:程序博客网 时间:2024/05/16 06:16
给定一个数组和一个特定的数,使得数组中的两个数等于这个特定的数。找出这两个数的下标。
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].class Solution(object): #新建类Solution,使用object继承 def twoSum(self, nums, target): #定义方法twosum,self代表类的实例,在定义方法时是必须有的。 """ :type nums: List[int] :type target: int :rtype: List[int] """ dic = dict() #利用python中的字典记录每个元素出现的位置,也就是其他语言的哈希表。 for index,value in enumerate(nums): #循环遍历字典中的对象,获得索引和值。 sub = target - value if sub in dic: return [dic[sub],index] else: dic[value] = index
字典说明
字典是由多个键及与其对应的值构成的键-值对组成。字典可以通过下面的方式创建:
phonebook={‘Alice’:'2341','Benth':'9201','Cecil':'3258'}
上面名字是键,电话号码是值。每个键与他的值之间用冒号(:)隔开,项之间用逗号(,)隔开,
整个字典用大括号{}括起来,字典中,键是唯一的,值不唯一。
dict函数,可以通过其他映射(比如其他字典)或(键,值)对儿的序列建立字典。
>>>items=[('name','Gumby'),('age',42)]
>>>d=dict(items)
>>>d
{'age':42,'name':'Gumpy'}
>>>d['name']
'Gumby'
dict函数也可以通过关键字参数来创建字典
>>>d=dict(name='Gumby',age=42)
>>>d{'age':42,'name':'Gumpy'}
enumerate()说明
- enumerate()是python的内置函数
- enumerate在字典上是枚举、列举的意思
- 对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
- enumerate多用于在for循环中得到计数
例如对于一个seq,得到:
- 1
- enumerate()返回的是一个enumerate对象,例如:
enumerate()使用
- 如果对一个列表,既要遍历索引又要遍历元素时,首先可以这样写:
- 上述方法有些累赘,利用enumerate()会更加直接和优美:
- list1 = ["这","是","一个","测试"]
- enumerate还可以接收第二个参数,用于指定索引起始值,如:
阅读全文
0 0
- python刷题笔记1--Two Sum
- leetcode 1 two sum 刷题学习笔记
- leetcode刷题笔记-two sum
- LeetCode刷题笔记 01 Two Sum
- LeetCode刷题笔记(Two Sum)
- Python 刷题日记:LeetCode: 1&15&16-Two Sum and 3Sum
- Python leetcode #1 Two Sum
- LeetCode笔记1--Two Sum
- LeetCode 第1题 Two sum (easy)——python
- [leetCode刷题笔记]371. Sum of Two Integers
- [LeetCode]1 Two Sum(C++,Python实现)
- leetcode【1+167 Two Sum 系列】【python】
- 【Leet Code- Algorithm】【1-Two Sum】【Python】
- LeetCode算法(Python)--1、Two Sum
- Python leetcode记录(1) -Two Sum
- 【LeetCode 1】Two Sum(Python)
- 【Leetcode】【python】Two Sum, Two Sum II
- LeetCodeOJ Two Sum (python)
- 博客第一天*有梦想谁都了不起
- 【BZOJ2440】[中山市选2011]完全平方数
- bzoj 5004: 开锁魔法II
- 剑指offer 编程题(13):链表遍历
- 关于android的OOM和内存溢出的出现与避免简单总结
- python刷题笔记1--Two Sum
- Bootstrap4(十三)
- Java并发编程:volatile关键字解析
- 设计模式之装饰设计模式
- Bootstrap4(十四)
- 最大子序列问题求解
- 【caffe】loss function、cost function和error
- 洛谷P3178 [HAOI2015]树上操作
- list方法总结