Skip to content

Commit

Permalink
feature: two sum revisit
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Jan 2, 2024
1 parent c4e5da2 commit 58437cb
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
6 changes: 4 additions & 2 deletions arrays/TwoSum.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import collections
from typing import List


# O(n) time || O(n) space
def two_sum(self, nums: List[int], target: int) -> List[int]:
dic = {}
dic = collections.defaultdict(int)
for i, num in enumerate(nums):
if target - num in dic:
return [dic[target - num], i]
return [i, dic[target - num]]

dic[num] = i
6 changes: 3 additions & 3 deletions arrays/test/test_two_sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@

class MyTestCase(unittest.TestCase):
def test_two_sum(self):
self.assertEqual([0, 1], two_sum(self, [2, 7, 11, 15], 9))
self.assertEqual([1, 0], two_sum(self, [2, 7, 11, 15], 9))

def test_two_sum_1(self):
self.assertEqual([1, 2], two_sum(self, [3, 2, 4], 6))
self.assertEqual([2, 1], two_sum(self, [3, 2, 4], 6))

def test_two_sum_2(self):
self.assertEqual([0, 1], two_sum(self, [3, 3], 6))
self.assertEqual([1, 0], two_sum(self, [3, 3], 6))


if __name__ == '__main__':
Expand Down

0 comments on commit 58437cb

Please sign in to comment.