File tree Expand file tree Collapse file tree 4 files changed +56
-0
lines changed
Expand file tree Collapse file tree 4 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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 ()
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments