Skip to content

Commit

Permalink
added python solution for 000.
Browse files Browse the repository at this point in the history
  • Loading branch information
pezy committed Dec 17, 2017
1 parent 9723639 commit dd9b545
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
6 changes: 5 additions & 1 deletion 000. Two Sum/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,8 @@

既然是配对,那么 kv 结构是非常合适的,于是上了 Hash 表。让 key 就是要找的 `b`,让 value 记录 `a` 的 index,也就是结果需要的索引。

这样思路就很简单明了了。
这样思路就很简单明了了。

## Python

基本与 C++ 的思路一致,只不过更简洁了。
24 changes: 24 additions & 0 deletions 000. Two Sum/solution.py
Original file line number Diff line number Diff line change
@@ -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])

0 comments on commit dd9b545

Please sign in to comment.