-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_sum.py
More file actions
36 lines (30 loc) · 799 Bytes
/
two_sum.py
File metadata and controls
36 lines (30 loc) · 799 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 1. Two Sum
# https://leetcode.com/problems/two-sum
import unittest
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i in range(len(nums)):
if nums[i] in dic:
return [dic[nums[i]], i]
else:
dic[target - nums[i]] = i
raise Exception('No solution')
class TestTwoSum(unittest.TestCase):
def test(self):
solution = Solution()
self.assertEqual(
solution.twoSum([2, 7, 11, 15], 9),
[0, 1]
)
self.assertEqual(
solution.twoSum([1, 2, 3, 9], 10),
[0, 3]
)
if __name__ == '__main__':
unittest.TestCase()