Skip to content

Commit 06a066f

Browse files
committed
#1. Two Sum
1 parent 74f2e9d commit 06a066f

File tree

2 files changed

+42
-8
lines changed

2 files changed

+42
-8
lines changed

Hash_Table/two_sums.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,23 @@
1-
# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
1+
# Given an array of integers nums and an integer target, return
2+
# indices of the two numbers such that they add up to target.
23

3-
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
4+
# You may assume that each input would have exactly one solution,
5+
# and you may not use the same element twice.
46

57
# You can return the answer in any order.
68

7-
8-
99
# Example 1:
10-
1110
# Input: nums = [2,7,11,15], target = 9
1211
# Output: [0,1]
1312
# Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
14-
# Example 2:
1513

14+
# Example 2:
1615
# Input: nums = [3,2,4], target = 6
1716
# Output: [1,2]
18-
# Example 3:
1917

18+
# Example 3:
2019
# Input: nums = [3,3], target = 6
2120
# Output: [0,1]
22-
2321

2422
# Constraints:
2523

Two_Pointers/two_sums.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Given an array of integers nums and an integer target, return
2+
# indices of the two numbers such that they add up to target.
3+
4+
# You may assume that each input would have exactly one solution,
5+
# and you may not use the same element twice.
6+
7+
# You can return the answer in any order.
8+
9+
# Example 1:
10+
# Input: nums = [2,7,11,15], target = 9
11+
# Output: [0,1]
12+
# Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
13+
14+
# Example 2:
15+
# Input: nums = [3,2,4], target = 6
16+
# Output: [1,2]
17+
18+
# Example 3:
19+
# Input: nums = [3,3], target = 6
20+
# Output: [0,1]
21+
22+
# Constraints:
23+
24+
# 2 <= nums.length <= 104
25+
# -109 <= nums[i] <= 109
26+
# -109 <= target <= 109
27+
# Only one valid answer exists.
28+
29+
class Solution:
30+
def twoSum(self, nums: int, target: int) -> int:
31+
hash_tbl = {}
32+
for i, n in enumerate(nums):
33+
c = target - n
34+
if c in hash_tbl:
35+
return [hash_tbl[c], i]
36+
hash_tbl[n] = i

0 commit comments

Comments
 (0)