[LeetCode]#167. Two Sum II — Input array is sorted

Fatboy Slim
1 min readMar 24, 2020

--

Environment : Python 3.7

Key technique: Hash table

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

Analysis:

This is nothing new with #1 Two Sum

Solution:

class Solution:
def twoSum(self, nums, target):
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+1, hash[target-nums[i]]+1]
return []

Submitted result:

Reference:

https://medium.com/@havbgbg68/leetcode-1-two-sum-python-8d77c223abd3

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet