diff --git a/source/_posts/leetcode-1-two-sum-md.md b/source/_posts/leetcode-1-two-sum-md.md index 26dfcee..2ec6eb3 100644 --- a/source/_posts/leetcode-1-two-sum-md.md +++ b/source/_posts/leetcode-1-two-sum-md.md @@ -1,6 +1,6 @@ --- title: leetcode-1-two-sum -tags: ["leetcode"] +tags: ["leetcode", "solution"] date: 2019-11-24 21:06:37 --- @@ -25,11 +25,11 @@ Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. ``` -题意很简单,就是给一个list,然后给定一个target,需要从list中找到两个数的和是target,然后输出这两个数的下标。需要注意的是每个元素只能用一次。 +题意很简单,就是给一个list,然后给定一个target,需要从list中找到两个数的和是target,然后输出这两个数的下标。需要注意的是每个元素只能用一次,另外输出的list中元素的顺序不影响结果。 我很快就完成了,但是第一版代码是错的,代码如: -```python3 +```python class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: m = dict() @@ -45,7 +45,7 @@ class Solution: 然后很快又改好了,加了判断条件,代码如: -```python3 +```python class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: m = dict() @@ -59,7 +59,7 @@ class Solution: 然后又WA了。。。嗯,仔细分析了一下,发现test case是[3,3] 6的时候,输出是空。嗯,分支条件写错了。不应该判断两个数字都在字典里面,因为如果有两个相同的元素的话只有一个会加入到字典中。为了解决这个问题,嗯,直接换个写法就好,如: -```python3 +```python class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: m = dict() @@ -72,7 +72,22 @@ class Solution: 嗯,总算AC了。我感觉每天一题的目标估计是要GG了。 +稍微看了下题解和别人的代码,我发现这么写更加优雅: + +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + m = dict() + for i, n in enumerate(nums): + if target-n in m: + return [m[target - n], i] + if n not in m: + m[n] = i +``` + # Refer [1. Two Sum](https://leetcode.com/problems/two-sum/) + +[1. Two Sum](https://leetcode.com/articles/two-sum/) # Appendix