Skip to content

Commit 791b275

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 1 Two Sum
1 parent 8607c5b commit 791b275

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
44

55
## Leetcode Problems & Solutions 💻
66

7+
- [1 Two Sum](https://leetcode.com/problems/two-sum/description/)
78
- [26 Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/)
89
- [27 Remove Element](https://leetcode.com/problems/remove-element/description/)
910
- [45 Jump Game II](https://leetcode.com/problems/jump-game-ii/description/)

awesome_python_leetcode/_1_two_sum.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def twoSum(self, nums: List[int], target: int) -> List[int]:
6+
"""
7+
Given an array of integers nums and an integer target, return
8+
indices of the two numbers such that they add up to target.
9+
10+
You may assume that each input would have exactly one solution,
11+
and you may not use the same element twice.
12+
13+
You can return the answer in any order.
14+
"""
15+
values = {}
16+
for i, n in enumerate(nums):
17+
diff = target - n
18+
if diff in values:
19+
return [values[diff], i]
20+
values[n] = i
21+
return

tests/test_1_two_sum.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._1_two_sum import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "target", "expected"],
10+
argvalues=[
11+
([2, 7, 11, 15], 9, [0, 1]),
12+
([3, 2, 4], 6, [1, 2]),
13+
([3, 3], 6, [0, 1]),
14+
],
15+
)
16+
def test_func(nums: List[int], target: int, expected: List[int]):
17+
two_sum = Solution().twoSum(nums, target)
18+
assert two_sum == expected

0 commit comments

Comments
 (0)