diff --git a/000. Two Sum/README.md b/000. Two Sum/README.md index 1e759dc..28825ed 100644 --- a/000. Two Sum/README.md +++ b/000. Two Sum/README.md @@ -11,4 +11,8 @@ 既然是配对,那么 kv 结构是非常合适的,于是上了 Hash 表。让 key 就是要找的 `b`,让 value 记录 `a` 的 index,也就是结果需要的索引。 -这样思路就很简单明了了。 \ No newline at end of file +这样思路就很简单明了了。 + +## Python + +基本与 C++ 的思路一致,只不过更简洁了。 \ No newline at end of file diff --git a/000. Two Sum/solution.py b/000. Two Sum/solution.py new file mode 100644 index 0000000..bd6c0b9 --- /dev/null +++ b/000. Two Sum/solution.py @@ -0,0 +1,24 @@ +#!python3 + + +class Solution: + def twoSum(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[int] + """ + dic = {} + for index, num in enumerate(nums): + if num in dic: + return [dic[num], index] + dic[target - num] = index + + +if __name__ == "__main__": + nums = [2, 7, 11, 15] + target = 9 + assert (Solution().twoSum(nums, target) == [0, 1]) + nums = [3, 2, 4] + target = 6 + assert (Solution().twoSum(nums, target) == [1, 2])