两数之和
【描述】
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
你可以按任意顺序返回答案。
【样例】
(1)记住enumerate(nums)这个函数可以同时遍历下标和迭代对象的值;
(2)最坏时间复杂度为O(N),N是数组的数量,通过哈希表的形式,每一个num找target-num的时间都为O(1);空间复杂度为O(N),哈希表的开销;以空间换时间;
(3)哈希表法,找num1+num2=target,循环遍历列表,找到一个num1后便要找num2;这时num2 = target-num1;即已经知道num2的值,去找他的小标,最省时间的办法是哈希表O(1)
(4)也确保了自己跟自己不想加;如nums = [3,3];target = 6;字典相同的键加不进去,返回的可能是[0,0],便成了自己和自己相加;
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
length = len(nums) #原数组的长度
dict = {} #记录元素下标
for i,num in enumerate(nums): #有下标和当前元素的值
if target-num in dict:
return [dict[target-num],i]
#遍历到num时,判断一下target-num是否在字典中,若在便返回;
else:
dict[num] = i #若未在字典中就把当前元素作为键,当前元素的下标作为值
return []
(1)暴力枚举法
(2)让数组中每两个数都互相加一次,判断是否等于terget;
(3)最坏的情况时间复杂度为O(N**2)【(n-1)+(n-2)+......+1=(n**2)/2】,最好的情况时间复杂度O(1),只运行一次;空间复杂度O(1)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
length = len(nums)
for j in range(length-1):
for m in range(j+1,length):
if nums[m]+nums[j] == target:
return j,m