刷lc不为其他,只为工程能力扩展与思维提升!
请看github: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].
代码语言:javascript复制# Runtime: 20 ms, faster than 100.00% of Python online submissions for Two Sum.
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map = {}
for i in range(len(nums)):
if nums[i] not in map:
map[target - nums[i]] = i
else:
return map[nums[i]], i
return -1, -1
代码语言:javascript复制# Runtime: 1192 ms, faster than 33.33% of Python online submissions for Two Sum.
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
temp = target - nums[i]
new_nums = nums[:i] nums[i 1:]
if temp in new_nums :
j = new_nums.index(temp) 1
return [i, j]
return []