最近开始刷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.
这里限制的是每个输入只有1个解,同一个元素不能用两次
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = []
[[result.extend([j, i]) for i in range(len(nums)) if nums[i] + nums[j] == target and i != j and result == []] for j in range(len(nums))]
return result
算法复杂度n**2
在官网中有一个复杂度为n的算法,如下
class Solution(object):
def twoSum(self, nums, target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i
这里,他用了字典来解决该问题,dict[wanted_result] = position,具体思路是重头遍历数组
然后,检查对于某个位置的某个元素是否在一个对应的指定位置存在一个希望的结果存在与字典中,由于有唯一解因此必定存在一个解.
eg:
也就是说是否
1--5
4--2
3--3
5--1
2--4
6--0
这些配对存在
具体步骤如下:
list=[1,4,3,5,2,6], target = 6
字典dict = {}
询问是否list[0]=1在字典中
否
加入5:0 (第0个要加list[0])
dict[6-list[0]]=dict[5]=0
询问是否list[1]=4在字典中
否
加入2:1
dict[6-list[1]]=dict[2]=1
询问是否list[2]=3在字典中
否
加入3:2
dict[6-list[2]]=dict[3]=2
询问是否list[3]=5在字典中
是dict[5] = 0
返回[dict[5], 3] == [0, 3]
总结:
在少量数据需要快速计算的情况下,我的方法比较快
在大量数据需要快速计算的情况下,复杂度为n的算法的方法比较快
GitHub: https://github.com/DinnerHowe/LeetCode.git