def twoSum(self, num, target):
d = {}
for i in range(len(num)):
if num[i] in d.keys():
return (d[num[i]]+1, i+1)
else:
d[target - num[i]] = i
Why time limit exceeded in python? (Two sum problem)
the trick might be num[i] in d.keys()
, the keys will be expanded, actually you should use num[i] in d
, or d.has_key(num[i])
, to see the differences, here: 'has_key()' or 'in'?
Hi,I don't know whether you have solved it.I just tried to solve it today, and in the last,my codes got accepted with 172ms.
the codes is here:
def twoSum(self, num, target):
dic={}
for i in range(len(num)):
sub=target-num[i]
if sub in dic:
return (dic[sub],i+1)
else:
dic[num[i]]=i+1
return (-1,-1)
Thanks all for the answers about the difference between "num[i] in d.keys()" and "d.has_key(num[i])".