Skip to content

Commit ac7b4fc

Browse files
committed
Adds medium two pointer exercise
1 parent 31c0ef1 commit ac7b4fc

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

167.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from typing import List
2+
import unittest
3+
4+
5+
class Solution:
6+
def twoSum(self, numbers: List[int], target: int) -> List[int]:
7+
i = 0
8+
j = len(numbers) - 1
9+
10+
while i < j:
11+
sum = numbers[i] + numbers[j]
12+
13+
if sum == target:
14+
return [i + 1, j + 1]
15+
elif sum > target:
16+
j -= 1
17+
elif sum < target:
18+
i += 1
19+
20+
return [-1, -1]
21+
22+
23+
class Tests(unittest.TestCase):
24+
def test_one(self):
25+
self.assertEqual(Solution().twoSum(numbers=[2, 7, 11, 15], target=9), [1, 2])
26+
27+
def test_two(self):
28+
self.assertEqual(Solution().twoSum(numbers=[2, 3, 4], target=6), [1, 3])
29+
30+
def test_three(self):
31+
self.assertEqual(Solution().twoSum(numbers=[-1, 0], target=-1), [1, 2])
32+
33+
34+
if __name__ == "__main__":
35+
unittest.main()

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
| -------------- | ---------------------- | ------------------------------------------------------------------------------------ |
33
| 1.py | Hash table | https://leetcode.com/problems/two-sum/ |
44
| 35.py | Binary Search | https://leetcode.com/problems/search-insert-position/ |
5+
| 167.py | Two pointers | https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ |
56
| 888.py | Hash table | https://leetcode.com/problems/fair-candy-swap |
67
| 977.py | Sorting | https://leetcode.com/problems/squares-of-a-sorted-array/ |
78
| 1051.py | | |

0 commit comments

Comments
 (0)