题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
题意:数组中两个数相加,使结果等于某个给定的数,返回这两个数的下标。
leetcode的第一题:1. Two Sum
第一种方法,用了字典数据结构,比较炫酷,但是不能解决输入nums=[0,3,4,0],target=0的问题:
class Solution(object):
def twoSum(self, nums, target): #类里面的函数自带self参数,self可以在函数里用,而这个self也是使用时自动传递过去的3.0版本里需要用 print(a)
4、字典的数据结构
'''
第二种简单的方法:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
list_len = len(nums)
for i in range(list_len):
for j in range(i+1,list_len):
if nums[i] + nums[j] == target:
return [i,j]
'''
笔记:
1、 range()函数的用法:
>>>
range
(
1
,
5
)
#代表从1到5(不包含5)
[
1
,
2
,
3
,
4
]
>>>
range
(
1
,
5
,
2
)
#代表从1到5,间隔2(不包含5)
[
1
,
3
]
>>>
range
(
5
)
#代表从0到5(不包含5)
[
0
,
1
,
2
,
3
,
4
]
|
'''