Skip to content

Commit 8ec437f

Browse files
authored
Merge pull request algorithm004-01#407 from IATF/master
381-Week 02
2 parents 212a929 + 01d105e commit 8ec437f

File tree

4 files changed

+56
-0
lines changed

4 files changed

+56
-0
lines changed

Week 02/id_381/leetcode-1.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class Solution:
2+
def twoSum(self, nums: list, target: int) -> list:
3+
tmp_dict = {}
4+
for i in range(len(nums)):
5+
sub = target - nums[i]
6+
if sub in tmp_dict:
7+
if tmp_dict[sub] != i:
8+
return [i, tmp_dict[sub]]
9+
tmp_dict[nums[i]] = i

Week 02/id_381/leetcode-242.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
两字符串各个字符数量相减为0
3+
"""
4+
5+
class Solution:
6+
def isAnagram(self, s: str, t: str) -> bool:
7+
# 长度不等,直接返回False
8+
if len(s) != len(t):
9+
return False
10+
counter = {}
11+
for i in s:
12+
if i not in counter:
13+
counter[i] = 1
14+
else:
15+
counter[i] += 1
16+
for j in t:
17+
if j not in counter:
18+
return False
19+
counter[j] -= 1
20+
# 查看最后的结果是否为0
21+
for key, value in counter.items():
22+
if value != 0:
23+
return False
24+
return True

Week 02/id_381/leetcode-49.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from collections import defaultdict
2+
class Solution:
3+
def groupAnagrams(self, strs: list) -> list:
4+
tmp_dict = defaultdict(list)
5+
for i, item in enumerate(strs):
6+
tmp = ''.join(sorted(item))
7+
# 与上面的相比,这里直接加上item会更好
8+
tmp_dict[tmp].append(item)
9+
return tmp_dict.values()

Week 02/id_381/leetcode-94.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def inorderTraversal(self, root) -> list:
3+
data = []
4+
stack = []
5+
current = root
6+
# 需要注意current和stack同时为None的时候才能跳出循环
7+
while current or stack:
8+
while current:
9+
stack.append(current)
10+
current = current.left
11+
pop_node = stack.pop()
12+
data.append(pop_node.val)
13+
current = pop_node.right
14+
return data

0 commit comments

Comments
 (0)