1. Two Sum (map )

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].


20180325
用 key in dict: 判断效率更高!!!
时间复杂度 o(n)
空间复杂度 o(n)
 1 class Solution:
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         n_dict = {}
 9         for i,item in enumerate(nums):
10             val = target - item
11             if item in n_dict:
12                 return [n_dict[item],i]
13             else:
14                 n_dict[val] = i

 

posted @ 2018-02-06 23:59  乐乐章  阅读(167)  评论(0编辑  收藏  举报