python leetcode
"""
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
"""
第一种比较简单的方法
class solution(object):
def twoSum(self,listnums,target):
for i in listnums:
for j in listnums:
if i != j:
if target == i+j:
return listnums.index(i),listnums.index(j)
s = solution()
s.twoSum([1,2,3,4],7)
第二种比较好的方式
class Solution(object):
def twoSum(self, nums, target):
dic = dict()
for index,value in enumerate(nums):
sub = target - value
if sub in dic:
return [dic[sub],index]
else:
dic[value] = index
每个年龄,鞭策自己尽力前行的理由都不一样,大家且行且珍惜