Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions kaakxixi/sum_two_nums.md → kaakxixi/readme.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
LeetCode 1 两数之和
2018-12-05
代码提交地址 https://leetcode-cn.com/problems/two-sum/submissions/

算法分析:

方法1. 整体时间复杂度为O(n^2). 由于python中的list对象实际上是链表,其查询效率为 O(n), 即这里的if 语句if num in nums复杂度为O(n),
Expand Down
10 changes: 6 additions & 4 deletions kaakxixi/sum_two_nums.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
"""
"""方法1是使用list查询差值"""
class Solution(object):
def twoSum(self, nums, target):
"""
Expand All @@ -23,20 +24,21 @@ def twoSum(self, nums, target):
return [i,nums.index(num)]


"""方法2是使用dict查询差值"""
def twoSum2(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#创建一个空字典
d = {}
dic = {}
for i in range(len(nums)):
num = target - nums[i]
#字典d中存在nums[i]时
if nums[i] in d:
return d[nums[i]],i
if nums[i] in dic:
return dic[nums[i]],i
#否则往字典增加键/值对
else:
d[num] = i
dic[num] = i
#边往字典增加键/值对,边与nums[i]进行对比