LeetCode 001 Two Sum
题意
给一组数,判断里面是否有两个数的和等于target,输出这两个数的下标
题解
首先枚举每一个数然后在二分查找被加数肯定能过,复杂度为O(nlog(n));
用python写map的话更简单一些,key为List里面的数,value为下标,每次判断被加数是否在map里,复杂度也是O(nlog(n)),代码如下
代码
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
mymap = {}
for index, num in enumerate(nums):
if target - num in mymap:
return [mymap[target - num] + 1, index + 1]
mymap[num] = index