[LeetCode]#1 Two Sum
1 min readMar 10, 2020
Environment : Python 3.7
Key technique: Hash table or Dictionary
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Analysis:
We need search two numbers which sum is as target and output their location.
Solution:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hash={}
for i in range(0,len(nums)):
hash[nums[i]]=i
for i in range(0,len(nums)):
if target-nums[i] in hash:
if hash[target-nums[i]] != i:
return [i, hash[target-nums[i]]]
return []
Submitted result:
Lesson learn:
This problem let me know that Hash table can reduce much computed time than Brute Force.
Reference:
https://medium.com/@havbgbg68/leetcode-1-two-sum-python-8d77c223abd3