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].
LeetCode:链接
暴力解法时间复杂度是O(n*n),不可以这么做。如果是有序的,用头指针和尾指针。如果是无序的,用字典的形式。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) < 2:
return None
my_dict = {}
for i in range(len(nums)):
if nums[i] not in my_dict:
my_dict[target-nums[i]] = i
else:
return [my_dict[nums[i]], i]