Skip to content

Commit 9f01282

Browse files
committed
Solution two sum problem at leetcode
1 parent 23954ef commit 9f01282

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Diff for: leetcode-daily_interview_problem/two_sum.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
'''
2+
Two Sum - Leetcode #1
3+
4+
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
5+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
6+
7+
Example:
8+
Given nums = [2, 7, 11, 15], target = 9,
9+
Because nums[0] + nums[1] = 2 + 7 = 9,
10+
return [0, 1].
11+
'''
12+
class Solution(object):
13+
def twoSum(self, nums, target):
14+
"""
15+
:type nums: List[int]
16+
:type target: int
17+
:rtype: List[int]
18+
"""
19+
map_nums = {}
20+
n = len(nums)
21+
for j in range(n):
22+
map_nums[nums[j]] = j
23+
for i in range(n):
24+
comp = target - nums[i]
25+
if comp in map_nums and i != map_nums[comp]:
26+
return [i, map_nums[comp]]
27+
return []
28+

0 commit comments

Comments
 (0)