Leetcode-Algorithms Two Sum
阿新 • • 發佈:2019-01-30
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
給出一個integer數列和一個integer,return一個包含 在給出的數列中兩個數之和是給出的integer的index的 數列。只有唯一解。
這是一個最簡單的方法,但是runtime太高。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for p1 in range(len(nums)):
for p2 in range(p1+1,len(nums)):
if((nums[p1]+nums[p2]) == target):
return [p1,p2]
用雜湊runtime會快很多因為只有一個loop。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
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
當list的數不在dict的時候,target減這個數的值為key,value為此數。當list的數為在dict為key的時候查詢就完成了。