Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 62490bc

Browse files
committed
Create two_sum.py
1 parent 91dd1e4 commit 62490bc

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

‎arrays_hashing/two_sum.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Given an array of integers nums and an integer target, return the indices i and j such that nums[i] + nums[j] == target and i != j.
2+
# You may assume that every input has exactly one pair of indices i and j that satisfy the condition.
3+
# Return the answer with the smaller index first.
4+
# Example :
5+
# Input:
6+
# nums = [3,4,5,6], target = 7
7+
# Output: [0,1]
8+
9+
from typing import List
10+
11+
class Solution:
12+
def twoSum(self, nums: List[int], target: int) -> List[int]:
13+
14+
hashmap = {}
15+
16+
for i , n in enumerate(nums):
17+
diff = target - n
18+
if diff in hashmap:
19+
return [hashmap[diff],i]
20+
else:
21+
hashmap[n] = i
22+
23+
print(Solution().twoSum([3,4,5,6],7))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /