1. Two Sum
题目
给你一个列表nums和一个数字target,如果列表里面有两个数之和等于target,则返回两个数字的下坐标,这两个数不能为同一个数。(假设总会有这两个数)
python
时间复杂度O(n^2)
# -*- coding:utf-8 -*-
class Solution(object): # O(n^2)
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for num in nums:
i = nums.index(num)
j = [j for j,v in enumerate(nums) if v==(target-num) and j!=i]
if j:
return [i, j[0]]
s = Solution()
print(s.twoSum([0, 4, 3, 0], 0))
时间复杂度O(n)
# -*- coding:utf-8 -*-
class Solution(object): # O(n)
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map = {}
for index, num in enumerate(nums):
if num in map:
return [map[num], index]
else:
map[target-num] = index
s = Solution()
print(s.twoSum([0, 4, 3, 0], 0))