8000 Two Sum · Quzijia/LeetCode@ed5e26c · GitHub
[go: up one dir, main page]

Skip to content

Commit ed5e26c

Browse files
committed
Two Sum
1 parent 5fad3db commit ed5e26c

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Array/Easy/1.Two Sum.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# 题目
2+
3+
给定一个整数的数组nums,返回相加为target的两个数字的索引值。
4+
5+
假设每次输入都只有一个答案,并且不会使用同一个元素两次。
6+
7+
**举例:**
8+
9+
``` stylus
10+
Given nums = [2, 7, 11, 15], target = 9,
11+
12+
Because nums[0] + nums[1] = 2 + 7 = 9,
13+
return [0, 1].
14+
```
15+
16+
# 思路
17+
18+
最初,我的解题思路是最简单的遍历,如果数组nums的元素a小于target,那么就在数组中寻找另外一个b,使a+b=target。
19+
20+
``` python
21+
class Solution(object):
22+
def twoSum(self, nums, target):
23+
"""
24+
:type nums: List[int]
25+
:type target: int
26+
:rtype: List[int]
27+
"""
28+
result = []
29+
for i, each in enumerate(nums):
30+
if abs(target-each) >=0 and i not in result:
31+
try:
32+
tmp = nums.index(target - each)
33+
if tmp != i:
34+
result.append(i)
35+
result.append(tmp)
36+
except:
37+
continue
38+
return result
39+
```
40+
41+
运行通过,但是运行速度特别慢!Beats才20%+。list的index操作时间复杂度为O(1),list的append操作时间复杂度也为O(1)。list的not in时间复杂度为O(n),在算上循环,总共时间复杂度为O(n^2)?所以才这么慢吧....
42+
43+
继续想一些更高级的解决办法。
44+
45+
使用哈希表,也就是散列表,在Python就是字典。使用方法很巧妙,直接看代码吧!
46+
47+
``` python
48+
class Solution(object):
49+
def twoSum(self, nums, target):
50+
"""
51+
:type nums: List[int]
52+
:type target: int
53+
:rtype: List[int]
54+
"""
55+
if len(nums) <= 1:
56+
return False
57+
buff_dict = {}
58+
for i in range(len(nums)):
59+
if nums[i] in buff_dict:
60+
return [buff_dict[nums[i]], i]
61+
else:
62+
buff_dict[target - nums[i]] = i
63+
```
64+
65+
Beats 90%+。
66+
67+

0 commit comments

Comments
 (0)
0