├── 50
├── 1.py
├── 11.py
├── 14.py
├── 19.py
├── 2.py
├── 20.py
├── 21.py
├── 23.py
├── 24.py
├── 25.py
├── 26.py
├── 27.py
├── 28.py
├── 3.py
├── 33.py
├── 34.py
├── 35.py
├── 38.py
├── 46.py
├── 47.py
├── 48.py
├── 49.py
├── 50.py
├── 6.py
├── 7.py
├── 8.py
├── 9.py
└── README.md
├── 100
├── 100.py
├── 53.py
├── 54.py
├── 58.py
├── 59.py
├── 74.py
├── 94.py
├── 98.py
├── 99.py
└── README.md
├── 150
├── 105.py
├── 144.py
├── 145.py
└── README.md
├── 200
├── 151.py
├── 165.py
├── 171.py
├── 172.py
└── README.md
├── 250
├── 204.py
├── 205.py
├── 206.py
├── 226.py
├── 237.py
├── 240.py
└── README.md
├── 300
├── 263.py
├── 264.py
└── README.md
├── 350
├── 349.py
├── 350.py
└── README.md
├── 400
├── 367.py
├── 380.py
├── 382.py
├── 383.py
├── 387.py
├── 389.py
├── 392.py
├── 394.py
├── 400.py
└── README.md
├── 450
├── 404.py
├── 409.py
├── 412.py
├── 414.py
├── 415.py
├── 434.py
├── 441.py
├── 442.py
├── 445.py
├── 448.py
├── 450.py
└── README.md
├── 500
├── 451.py
├── 454.py
├── 455.py
├── 461.py
├── 468.py
├── 476.py
├── 482.py
├── 485.py
├── 492.py
├── 500.py
└── README.md
├── 550
├── 504.py
├── 507.py
├── 513.py
├── 515.py
├── 520.py
├── 530.py
├── 537.py
├── 539.py
└── README.md
├── 600
├── 551.py
├── 557.py
├── 572.py
├── 593.py
└── README.md
├── 650
├── 606.py
├── 617.py
├── 633.py
└── README.md
├── 700
├── 654.py
├── 657.py
├── 671.py
├── 674.py
├── 680.py
├── 693.py
└── README.md
├── 750
├── 709.py
├── 717.py
├── 724.py
├── 725.py
├── 728.py
├── 744.py
├── 747.py
└── README.md
├── 800
├── 771.py
├── 783.py
├── 791.py
├── 796.py
└── README.md
├── 950
├── 905.py
├── 908.py
├── 917.py
├── 922.py
├── 929.py
└── README.md
├── README.md
├── blog
├── 382.md
└── README.md
└── tests
└── tree.py
/100/100.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def isSameTree(self, p, q):
10 | """
11 | :type p: TreeNode
12 | :type q: TreeNode
13 | :rtype: bool
14 | """
15 | if (not p and q) or (p and not q):
16 | return False
17 | if not p and not q:
18 | return True
19 | return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
20 |
--------------------------------------------------------------------------------
/100/53.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def maxSubArray(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: int
6 | """
7 | if not nums:
8 | return
9 | max_val, cur_sum = nums[0], float('-inf')
10 | for n in nums:
11 | cur_sum = max(n, cur_sum + n)
12 | max_val = max(max_val, cur_sum)
13 | return max_val
14 |
--------------------------------------------------------------------------------
/100/54.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def spiralOrder(self, matrix):
3 | """
4 | :type matrix: List[List[int]]
5 | :rtype: List[int]
6 | """
7 | if not matrix or len(matrix[0]) == 0:
8 | return []
9 | ret = []
10 | start, m, n = 0, len(matrix), len(matrix[0])
11 | while start * 2 < m and start * 2 < n:
12 | col = row = start
13 | # left -> right
14 | while col < n - start:
15 | ret.append(matrix[row][col])
16 | col += 1
17 | # top -> bottom
18 | if m - 2 * start > 1 and row < m - start:
19 | row += 1
20 | col -= 1
21 | while row < m - start:
22 | ret.append(matrix[row][col])
23 | row += 1
24 | # right -> left
25 | if m - 2 * start > 1 and n - 2 * start > 1 and col >= start:
26 | col -= 1
27 | row -= 1
28 | while col >= start:
29 | ret.append(matrix[row][col])
30 | col -= 1
31 | # bottom -> top
32 | if m - 2 * start > 1 and n - 2 * start > 1 and row > start:
33 | row -= 1
34 | col += 1
35 | while row > start:
36 | ret.append(matrix[row][col])
37 | row -= 1
38 | start += 1
39 | return ret
--------------------------------------------------------------------------------
/100/58.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def lengthOfLastWord(self, s):
3 | """
4 | :type s: str
5 | :rtype: int
6 | """
7 | ret = 0
8 | for c in s.strip()[::-1]:
9 | if c == ' ':
10 | break
11 | ret += 1
12 | return ret
--------------------------------------------------------------------------------
/100/59.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def generateMatrix(self, n):
3 | """
4 | :type n: int
5 | :rtype: List[List[int]]
6 | """
7 | ret = [[0 for i in range(n)] for j in range(n)]
8 | v, start = 1, 0
9 | while start * 2 < n:
10 | col = row = start
11 | # left -> right
12 | while col < n - start:
13 | ret[row][col] = v
14 | col += 1
15 | v += 1
16 | # top -> bottom
17 | if n - 2 * start > 1 and row < n - start:
18 | row += 1
19 | col -= 1
20 | while row < n - start:
21 | ret[row][col] = v
22 | row += 1
23 | v += 1
24 | # right -> left
25 | if n - 2 * start > 1 and n - 2 * start > 1 and col >= start:
26 | col -= 1
27 | row -= 1
28 | while col >= start:
29 | ret[row][col] = v
30 | col -= 1
31 | v += 1
32 | # bottom -> top
33 | if n - 2 * start > 1 and n - 2 * start > 1 and row > start:
34 | row -= 1
35 | col += 1
36 | while row > start:
37 | ret[row][col] = v
38 | v += 1
39 | row -= 1
40 | start += 1
41 | return ret
--------------------------------------------------------------------------------
/100/74.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def searchMatrix(self, matrix, target):
3 | """
4 | :type matrix: List[List[int]]
5 | :type target: int
6 | :rtype: bool
7 | """
8 | if not matrix or not matrix[0]:
9 | return False
10 | rows = len(matrix)
11 | while rows > 0:
12 | if matrix[rows - 1][0] < target:
13 | return self.bin_search(matrix[rows - 1], target)
14 | elif matrix[rows - 1][0] == target:
15 | return True
16 | else:
17 | rows -= 1
18 | return False
19 |
20 | def bin_search(self, data, target):
21 | """
22 | :type data: List[int]
23 | :type target: int
24 | :rtype: bool
25 | """
26 | low, high = 0, len(data)
27 | while low < high:
28 | mid = low + (high - low) / 2
29 | if data[mid] == target:
30 | return True
31 | elif data[mid] < target:
32 | low = mid + 1
33 | else:
34 | high = mid
35 | return False
36 |
--------------------------------------------------------------------------------
/100/94.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def inorderTraversal(self, root):
10 | """
11 | :type root: TreeNode
12 | :rtype: List[int]
13 | """
14 | ret = []
15 | stack = []
16 | while root or stack:
17 | while root:
18 | stack.append(root)
19 | root = root.left
20 | if stack:
21 | t = stack.pop()
22 | ret.append(t.val)
23 | root = t.right
24 | return ret
25 |
--------------------------------------------------------------------------------
/100/98.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def isValidBST(self, root):
10 | """
11 | :type root: TreeNode
12 | :rtype: bool
13 | """
14 | ret = []
15 |
16 | def in_order(root):
17 | if not root:
18 | return
19 | in_order(root.left)
20 | ret.append(root.val)
21 | in_order(root.right)
22 |
23 | in_order(root)
24 | leng = len(ret)
25 | for k in range(leng - 1):
26 | if ret[k] >= ret[k + 1]:
27 | return False
28 | return True
29 |
--------------------------------------------------------------------------------
/100/99.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def __init__(self):
10 | self.first = None
11 | self.second = None
12 | self.pre = TreeNode(float('-inf'))
13 |
14 | def recoverTree(self, root):
15 | """
16 | :type root: TreeNode
17 | :rtype: void Do not return anything, modify root in-place instead.
18 | """
19 | self.inorder_traversal(root)
20 | self.first.val, self.second.val = self.second.val, self.first.val
21 |
22 | def inorder_traversal(self, root):
23 | if not root:
24 | return
25 | self.inorder_traversal(root.left)
26 | if not self.first and root.val <= self.pre.val:
27 | self.first = self.pre
28 | if self.first and root.val <= self.pre.val:
29 | self.second = root
30 | self.pre = root
31 | self.inorder_traversal(root.right)
32 |
--------------------------------------------------------------------------------
/100/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 51-100
2 |
3 | 53 [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)
4 | ```python
5 | class Solution(object):
6 | def maxSubArray(self, nums):
7 | """
8 | :type nums: List[int]
9 | :rtype: int
10 | """
11 | if not nums:
12 | return
13 | max_val, cur_sum = nums[0], float('-inf')
14 | for n in nums:
15 | cur_sum = max(n, cur_sum + n)
16 | max_val = max(max_val, cur_sum)
17 | return max_val
18 | ```
19 |
20 | 54 [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/)
21 | ```python
22 | class Solution(object):
23 | def spiralOrder(self, matrix):
24 | """
25 | :type matrix: List[List[int]]
26 | :rtype: List[int]
27 | """
28 | if not matrix or len(matrix[0]) == 0:
29 | return []
30 | ret = []
31 | start, m, n = 0, len(matrix), len(matrix[0])
32 | while start * 2 < m and start * 2 < n:
33 | col = row = start
34 | # left -> right
35 | while col < n - start:
36 | ret.append(matrix[row][col])
37 | col += 1
38 | # top -> bottom
39 | if m - 2 * start > 1 and row < m - start:
40 | row += 1
41 | col -= 1
42 | while row < m - start:
43 | ret.append(matrix[row][col])
44 | row += 1
45 | # right -> left
46 | if m - 2 * start > 1 and n - 2 * start > 1 and col >= start:
47 | col -= 1
48 | row -= 1
49 | while col >= start:
50 | ret.append(matrix[row][col])
51 | col -= 1
52 | # bottom -> top
53 | if m - 2 * start > 1 and n - 2 * start > 1 and row > start:
54 | row -= 1
55 | col += 1
56 | while row > start:
57 | ret.append(matrix[row][col])
58 | row -= 1
59 | start += 1
60 | return ret
61 | ```
62 |
63 | 58 [Length of Last Word](https://leetcode.com/problems/length-of-last-word/)
64 | ```python
65 | class Solution(object):
66 | def lengthOfLastWord(self, s):
67 | """
68 | :type s: str
69 | :rtype: int
70 | """
71 | ret = 0
72 | for c in s.strip()[::-1]:
73 | if c == ' ':
74 | break
75 | ret += 1
76 | return ret
77 | ```
78 |
79 | 59 [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/)
80 | ```python
81 | class Solution(object):
82 | def generateMatrix(self, n):
83 | """
84 | :type n: int
85 | :rtype: List[List[int]]
86 | """
87 | ret = [[0 for i in range(n)] for j in range(n)]
88 | v, start = 1, 0
89 | while start * 2 < n:
90 | col = row = start
91 | # left -> right
92 | while col < n - start:
93 | ret[row][col] = v
94 | col += 1
95 | v += 1
96 | # top -> bottom
97 | if n - 2 * start > 1 and row < n - start:
98 | row += 1
99 | col -= 1
100 | while row < n - start:
101 | ret[row][col] = v
102 | row += 1
103 | v += 1
104 | # right -> left
105 | if n - 2 * start > 1 and n - 2 * start > 1 and col >= start:
106 | col -= 1
107 | row -= 1
108 | while col >= start:
109 | ret[row][col] = v
110 | col -= 1
111 | v += 1
112 | # bottom -> top
113 | if n - 2 * start > 1 and n - 2 * start > 1 and row > start:
114 | row -= 1
115 | col += 1
116 | while row > start:
117 | ret[row][col] = v
118 | v += 1
119 | row -= 1
120 | start += 1
121 | return ret
122 | ```
123 |
124 | 74 [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/)
125 | ```python
126 | class Solution(object):
127 | def searchMatrix(self, matrix, target):
128 | """
129 | :type matrix: List[List[int]]
130 | :type target: int
131 | :rtype: bool
132 | """
133 | if not matrix or not matrix[0]:
134 | return False
135 | rows = len(matrix)
136 | while rows > 0:
137 | if matrix[rows - 1][0] < target:
138 | return self.bin_search(matrix[rows - 1], target)
139 | elif matrix[rows - 1][0] == target:
140 | return True
141 | else:
142 | rows -= 1
143 | return False
144 |
145 | def bin_search(self, data, target):
146 | """
147 | :type data: List[int]
148 | :type target: int
149 | :rtype: bool
150 | """
151 | low, high = 0, len(data)
152 | while low < high:
153 | mid = low + (high - low) / 2
154 | if data[mid] == target:
155 | return True
156 | elif data[mid] < target:
157 | low = mid + 1
158 | else:
159 | high = mid
160 | return False
161 | ```
162 |
163 | 94 [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/description/)
164 | ```Python
165 | class Solution(object):
166 | def inorderTraversal(self, root):
167 | """
168 | :type root: TreeNode
169 | :rtype: List[int]
170 | """
171 | ret = []
172 | stack = []
173 | while root or stack:
174 | while root:
175 | stack.append(root)
176 | root = root.left
177 | if stack:
178 | t = stack.pop()
179 | ret.append(t.val)
180 | root = t.right
181 | return ret
182 | ```
183 |
184 | 98 [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)
185 | ```python
186 | class Solution(object):
187 | def isValidBST(self, root):
188 | """
189 | :type root: TreeNode
190 | :rtype: bool
191 | """
192 | ret = []
193 |
194 | def in_order(root):
195 | if not root:
196 | return
197 | in_order(root.left)
198 | ret.append(root.val)
199 | in_order(root.right)
200 | in_order(root)
201 | leng = len(ret)
202 | for k in range(leng - 1):
203 | if ret[k] >= ret[k + 1]:
204 | return False
205 | return True
206 | ```
207 |
208 | 99 [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/)
209 | ```
210 | class Solution(object):
211 |
212 | def __init__(self):
213 | self.first = None
214 | self.second = None
215 | self.pre = TreeNode(float('-inf'))
216 |
217 | def recoverTree(self, root):
218 | """
219 | :type root: TreeNode
220 | :rtype: void Do not return anything, modify root in-place instead.
221 | """
222 | self.inorder_traversal(root)
223 | self.first.val, self.second.val = self.second.val, self.first.val
224 |
225 | def inorder_traversal(self, root):
226 | if not root:
227 | return
228 | self.inorder_traversal(root.left)
229 | if not self.first and root.val <= self.pre.val:
230 | self.first = self.pre
231 | if self.first and root.val <= self.pre.val:
232 | self.second = root
233 | self.pre = root
234 | self.inorder_traversal(root.right)
235 | ```
236 |
237 | 100 [Same Tree](https://leetcode.com/problems/same-tree/)
238 | ```python
239 | class Solution(object):
240 | def isSameTree(self, p, q):
241 | """
242 | :type p: TreeNode
243 | :type q: TreeNode
244 | :rtype: bool
245 | """
246 | if (not p and q) or (p and not q):
247 | return False
248 | if not p and not q:
249 | return True
250 | return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
251 | ```
252 |
--------------------------------------------------------------------------------
/150/105.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def buildTree(self, preorder, inorder):
10 | """
11 | :type preorder: List[int]
12 | :type inorder: List[int]
13 | :rtype: TreeNode
14 | """
15 | if not preorder or not inorder:
16 | return None
17 | root = TreeNode(preorder[0])
18 | loc = inorder.index(preorder[0])
19 | left, right = inorder[0:loc], inorder[loc+1:]
20 | root.left = self.buildTree(preorder[1:len(left)+1], left)
21 | root.right = self.buildTree(preorder[len(left)+1:] ,right)
22 | return root
23 |
--------------------------------------------------------------------------------
/150/144.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def preorderTraversal(self, root):
10 | """
11 | :type root: TreeNode
12 | :rtype: List[int]
13 | """
14 | ret = []
15 | stack = []
16 | while root or stack:
17 | while root:
18 | ret.append(root.val)
19 | stack.append(root)
20 | root = root.left
21 | if stack:
22 | t = stack.pop()
23 | root = t.right
24 | return ret
25 |
26 |
--------------------------------------------------------------------------------
/150/145.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def postorderTraversal(self, root):
10 | """
11 | :type root: TreeNode
12 | :rtype: List[int]
13 | """
14 | ret = []
15 | stack = []
16 | while root or stack:
17 | while root:
18 | ret.append(root.val)
19 | stack.append(root)
20 | root = root.right
21 | if stack:
22 | top = stack.pop()
23 | root = top.left
24 | return ret[::-1]
25 |
26 |
--------------------------------------------------------------------------------
/150/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 101-150
2 |
3 | 105 [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
4 | ```
5 | class Solution(object):
6 | def buildTree(self, preorder, inorder):
7 | """
8 | :type preorder: List[int]
9 | :type inorder: List[int]
10 | :rtype: TreeNode
11 | """
12 | if not preorder or not inorder:
13 | return None
14 | root = TreeNode(preorder[0])
15 | loc = inorder.index(preorder[0])
16 | left, right = inorder[0:loc], inorder[loc+1:]
17 | root.left = self.buildTree(preorder[1:len(left)+1], left)
18 | root.right = self.buildTree(preorder[len(left)+1:] ,right)
19 | return root
20 | ```
21 |
22 | 144 [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/description/)
23 | ```Python
24 | class Solution(object):
25 | def preorderTraversal(self, root):
26 | """
27 | :type root: TreeNode
28 | :rtype: List[int]
29 | """
30 | ret = []
31 | stack = []
32 | while root or stack:
33 | while root:
34 | ret.append(root.val)
35 | stack.append(root)
36 | root = root.left
37 | if stack:
38 | t = stack.pop()
39 | root = t.right
40 | return ret
41 | ```
42 |
43 | 145 [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/description/)
44 | ```Python
45 | class Solution(object):
46 | def postorderTraversal(self, root):
47 | """
48 | :type root: TreeNode
49 | :rtype: List[int]
50 | """
51 | ret = []
52 | stack = []
53 | while root or stack:
54 | while root:
55 | ret.append(root.val)
56 | stack.append(root)
57 | root = root.right
58 | if stack:
59 | top = stack.pop()
60 | root = top.left
61 | return ret[::-1]
62 | ```
63 |
--------------------------------------------------------------------------------
/200/151.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def reverseWords(self, s):
3 | """
4 | :type s: str
5 | :rtype: str
6 | """
7 | tmp = s.split()
8 | return ' '.join(tmp[::-1])
--------------------------------------------------------------------------------
/200/165.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def compareVersion(self, version1, version2):
3 | """
4 | :type version1: str
5 | :type version2: str
6 | :rtype: int
7 | """
8 | v1 = version1.split('.')
9 | v2 = version2.split('.')
10 | k1, k2 = 0, 0
11 | while k1 < len(v1) and k2 < len(v2):
12 | if int(v1[k1]) > int(v2[k2]):
13 | return 1
14 | if int(v1[k1]) < int(v2[k2]):
15 | return -1
16 | k1 += 1
17 | k2 += 1
18 | while k1 < len(v1):
19 | if int(v1[k1]):
20 | return 1
21 | k1 += 1
22 | while k2 < len(v2):
23 | if int(v2[k2]):
24 | return -1
25 | k2 += 1
26 | return 0
--------------------------------------------------------------------------------
/200/171.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def titleToNumber(self, s):
3 | """
4 | :type s: str
5 | :rtype: int
6 | """
7 | ret = 0
8 | track = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7,
9 | 'H': 8, 'I': 9, 'J': 10, 'K': 11, 'L': 12, 'M': 13, 'N': 14,
10 | 'O': 15, 'P': 16, 'Q': 17, 'R': 18, 'S': 19, 'T': 20,
11 | 'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26}
12 | for k, v in enumerate(s):
13 | ret += track[v] * 26 ** (len(s) - 1 - k)
14 | return ret
15 |
--------------------------------------------------------------------------------
/200/172.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def trailingZeroes(self, n):
3 | """
4 | :type n: int
5 | :rtype: int
6 | """
7 | ret, carry = 0, 1
8 | while True:
9 | cnt = n / 5 ** carry
10 | if cnt == 0:
11 | return ret
12 | ret += cnt
13 | carry += 1
--------------------------------------------------------------------------------
/200/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 151-200
2 |
3 | 151 [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/submissions/)
4 | ```python
5 | class Solution(object):
6 | def reverseWords(self, s):
7 | """
8 | :type s: str
9 | :rtype: str
10 | """
11 | tmp = s.split()
12 | return ' '.join(tmp[::-1])
13 | ```
14 |
15 | 165 [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/)
16 | ```python
17 | class Solution(object):
18 | def compareVersion(self, version1, version2):
19 | """
20 | :type version1: str
21 | :type version2: str
22 | :rtype: int
23 | """
24 | v1 = version1.split('.')
25 | v2 = version2.split('.')
26 | k1, k2 = 0, 0
27 | while k1 < len(v1) and k2 < len(v2):
28 | if int(v1[k1]) > int(v2[k2]):
29 | return 1
30 | if int(v1[k1]) < int(v2[k2]):
31 | return -1
32 | k1 += 1
33 | k2 += 1
34 | while k1 < len(v1):
35 | if int(v1[k1]):
36 | return 1
37 | k1 += 1
38 | while k2 < len(v2):
39 | if int(v2[k2]):
40 | return -1
41 | k2 += 1
42 | return 0
43 | ```
44 |
45 | 171 [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/)
46 | ```python
47 | class Solution(object):
48 | def titleToNumber(self, s):
49 | """
50 | :type s: str
51 | :rtype: int
52 | """
53 | ret = 0
54 | track = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7,
55 | 'H': 8, 'I': 9, 'J': 10, 'K': 11, 'L': 12, 'M': 13, 'N': 14,
56 | 'O': 15, 'P': 16, 'Q': 17, 'R': 18, 'S': 19, 'T': 20,
57 | 'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26}
58 | for k, v in enumerate(s):
59 | ret += track[v] * 26 ** (len(s) - 1 - k)
60 | return ret
61 | ```
62 |
63 | 172 [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/)
64 | ```
65 | class Solution(object):
66 | def trailingZeroes(self, n):
67 | """
68 | :type n: int
69 | :rtype: int
70 | """
71 | ret, carry = 0, 1
72 | while True:
73 | cnt = n / 5 ** carry
74 | if cnt == 0:
75 | return ret
76 | ret += cnt
77 | carry += 1
78 | ```
79 |
--------------------------------------------------------------------------------
/250/204.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def countPrimes(self, n):
3 | """
4 | :type n: int
5 | :rtype: int
6 | """
7 | if n <= 2:
8 | return 0
9 | tmp = [1] * n
10 | tmp[0] = tmp[1] = 0
11 | for i in range(2, int(n**0.5) + 1):
12 | if tmp[i]:
13 | for j in range(2, (n - 1)/i+1):
14 | tmp[i*j] = 0
15 | return sum(tmp)
--------------------------------------------------------------------------------
/250/205.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def isIsomorphic(self, s, t):
3 | """
4 | :type s: str
5 | :type t: str
6 | :rtype: bool
7 | """
8 | len_s, len_t = len(s), len(t)
9 | if len_s != len_t:
10 | return False
11 | if len_s == len_t == 0:
12 | return True
13 | maps, mapt = {}, {}
14 | for a, v in zip(s, t):
15 | if not maps.get(a):
16 | maps[a] = v
17 | if not mapt.get(v):
18 | mapt[v] = a
19 | if maps[a] != v or mapt[v] != a:
20 | return False
21 | return True
--------------------------------------------------------------------------------
/250/206.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution(object):
8 | def reverseList(self, head):
9 | """
10 | :type head: ListNode
11 | :rtype: ListNode
12 | """
13 | pre = None
14 | while head:
15 | n, head.next = head.next, pre
16 | pre, head = head, n
17 | return pre
18 |
--------------------------------------------------------------------------------
/250/226.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def invertTree(self, root):
10 | """
11 | :type root: TreeNode
12 | :rtype: TreeNode
13 | """
14 | if not root:
15 | return None
16 | left = self.invertTree(root.left)
17 | right = self.invertTree(root.right)
18 | root.left = right
19 | root.right = left
20 | return root
21 |
--------------------------------------------------------------------------------
/250/237.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution(object):
8 | def deleteNode(self, node):
9 | """
10 | :type node: ListNode
11 | :rtype: void Do not return anything, modify node in-place instead.
12 | """
13 | p = node.next
14 | node.next, node.val = p.next, p.val
15 |
--------------------------------------------------------------------------------
/250/240.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def searchMatrix(self, matrix, target):
3 | """
4 | :type matrix: List[List[int]]
5 | :type target: int
6 | :rtype: bool
7 | """
8 | if not matrix:
9 | return False
10 | rows, cols = len(matrix) - 1, len(matrix[0]) - 1
11 | start = 0
12 | while rows >= 0 and cols >= start:
13 | if matrix[rows][start] == target:
14 | return True
15 | elif matrix[rows][start] > target:
16 | rows -= 1
17 | else:
18 | start += 1
19 | return False
--------------------------------------------------------------------------------
/250/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 201-250
2 |
3 | 204 [Count Primes](https://leetcode.com/problems/count-primes/)
4 | ```python
5 | class Solution(object):
6 | def countPrimes(self, n):
7 | """
8 | :type n: int
9 | :rtype: int
10 | """
11 | if n <= 2:
12 | return 0
13 | tmp = [1] * n
14 | tmp[0] = tmp[1] = 0
15 | for i in range(2, int(n**0.5) + 1):
16 | if tmp[i]:
17 | for j in range(2, (n - 1)/i+1):
18 | tmp[i*j] = 0
19 | return sum(tmp)
20 | ```
21 |
22 | 205 [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/)
23 | ```
24 | class Solution(object):
25 | def isIsomorphic(self, s, t):
26 | """
27 | :type s: str
28 | :type t: str
29 | :rtype: bool
30 | """
31 | len_s, len_t = len(s), len(t)
32 | if len_s != len_t:
33 | return False
34 | if len_s == len_t == 0:
35 | return True
36 | maps, mapt = {}, {}
37 | for a, v in zip(s, t):
38 | if not maps.get(a):
39 | maps[a] = v
40 | if not mapt.get(v):
41 | mapt[v] = a
42 | if maps[a] != v or mapt[v] != a:
43 | return False
44 | return True
45 | ```
46 |
47 | 206 [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)
48 | ```
49 | class Solution(object):
50 | def reverseList(self, head):
51 | """
52 | :type head: ListNode
53 | :rtype: ListNode
54 | """
55 | pre = None
56 | while head:
57 | n, head.next = head.next, pre
58 | pre, head = head, n
59 | return pre
60 | ```
61 |
62 | 226 [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/description/)
63 | ```python
64 | class Solution(object):
65 | def invertTree(self, root):
66 | """
67 | :type root: TreeNode
68 | :rtype: TreeNode
69 | """
70 | if not root:
71 | return None
72 | left = self.invertTree(root.left)
73 | right = self.invertTree(root.right)
74 | root.left = right
75 | root.right = left
76 | return root
77 | ```
78 |
79 | 237 [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)
80 | ```python
81 | class Solution(object):
82 | def deleteNode(self, node):
83 | """
84 | :type node: ListNode
85 | :rtype: void Do not return anything, modify node in-place instead.
86 | """
87 | p = node.next
88 | node.next, node.val = p.next, p.val
89 | ```
90 |
91 | 240 [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/)
92 | ```python
93 | class Solution(object):
94 | def searchMatrix(self, matrix, target):
95 | """
96 | :type matrix: List[List[int]]
97 | :type target: int
98 | :rtype: bool
99 | """
100 | if not matrix:
101 | return False
102 | rows, cols = len(matrix) - 1, len(matrix[0]) - 1
103 | start = 0
104 | while rows >= 0 and cols >= start:
105 | if matrix[rows][start] == target:
106 | return True
107 | elif matrix[rows][start] > target:
108 | rows -= 1
109 | else:
110 | start += 1
111 | return False
112 | ```
--------------------------------------------------------------------------------
/300/263.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def isUgly(self, num):
3 | """
4 | :type num: int
5 | :rtype: bool
6 | """
7 | if num <= 0:
8 | return False
9 | while num % 2 == 0:
10 | num /= 2
11 | while num % 3 == 0:
12 | num /= 3
13 | while num % 5 == 0:
14 | num /= 5
15 | if num == 1:
16 | return True
17 | return False
--------------------------------------------------------------------------------
/300/264.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def nthUglyNumber(self, n):
3 | """
4 | :type n: int
5 | :rtype: int
6 | """
7 | ugly = [1]
8 | t2 = t3 = t5 = 0
9 | while len(ugly) < n:
10 | while ugly[t2] * 2 <= ugly[-1]:
11 | t2 += 1
12 | while ugly[t3] * 3 <= ugly[-1]:
13 | t3 += 1
14 | while ugly[t5] * 5 <= ugly[-1]:
15 | t5 += 1
16 | ugly.append(min(ugly[t2]*2, ugly[t3]*3, ugly[t5]*5))
17 | return ugly[-1]
--------------------------------------------------------------------------------
/300/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 251-300
2 |
3 | 263 [Ugly Number](https://leetcode.com/problems/ugly-number/)
4 | ```python
5 | class Solution(object):
6 | def isUgly(self, num):
7 | """
8 | :type num: int
9 | :rtype: bool
10 | """
11 | if num <= 0:
12 | return False
13 | while num % 2 == 0:
14 | num /= 2
15 | while num % 3 == 0:
16 | num /= 3
17 | while num % 5 == 0:
18 | num /= 5
19 | if num == 1:
20 | return True
21 | return False
22 | ```
23 |
24 | 264 [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/)
25 | ```python
26 | class Solution(object):
27 | def nthUglyNumber(self, n):
28 | """
29 | :type n: int
30 | :rtype: int
31 | """
32 | ugly = [1]
33 | t2 = t3 = t5 = 0
34 | while len(ugly) < n:
35 | while ugly[t2] * 2<= ugly[-1]:
36 | t2 += 1
37 | while ugly[t3]*3 <= ugly[-1]:
38 | t3 += 1
39 | while ugly[t5] *5<= ugly[-1]:
40 | t5 += 1
41 | ugly.append(min(ugly[t2]*2, ugly[t3]*3, ugly[t5]*5))
42 | return ugly[-1]
43 | ```
--------------------------------------------------------------------------------
/350/349.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def intersection(self, nums1, nums2):
3 | """
4 | :type nums1: List[int]
5 | :type nums2: List[int]
6 | :rtype: List[int]
7 | """
8 | return list(set(nums1).intersection(set(nums2)))
9 |
--------------------------------------------------------------------------------
/350/350.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def intersect(self, nums1, nums2):
3 | """
4 | :type nums1: List[int]
5 | :type nums2: List[int]
6 | :rtype: List[int]
7 | """
8 | tmp_dict = dict()
9 | ret = []
10 | for i in nums1:
11 | tmp_dict[i] = tmp_dict[i] + 1 if tmp_dict.get(i) else 1
12 | for n in nums2:
13 | if tmp_dict.get(n) > 0:
14 | ret.append(n)
15 | tmp_dict[n] -= 1
16 | return ret
17 |
--------------------------------------------------------------------------------
/350/README.md:
--------------------------------------------------------------------------------
1 | # LeegtCode 301-350
2 |
3 | 349 [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/description/)
4 | ```Python
5 | class Solution(object):
6 | def intersection(self, nums1, nums2):
7 | """
8 | :type nums1: List[int]
9 | :type nums2: List[int]
10 | :rtype: List[int]
11 | """
12 | return list(set(nums1).intersection(set(nums2)))
13 | ```
14 |
15 | 350 [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/description/)
16 | ```Python
17 | class Solution(object):
18 | def intersect(self, nums1, nums2):
19 | """
20 | :type nums1: List[int]
21 | :type nums2: List[int]
22 | :rtype: List[int]
23 | """
24 | tmp_dict = dict()
25 | ret = []
26 | for i in nums1:
27 | tmp_dict[i] = tmp_dict[i] + 1 if tmp_dict.get(i) else 1
28 | for n in nums2:
29 | if tmp_dict.get(n) > 0:
30 | ret.append(n)
31 | tmp_dict[n] -= 1
32 | return ret
33 | ```
34 |
--------------------------------------------------------------------------------
/400/367.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def isPerfectSquare(self, num):
3 | """
4 | :type num: int
5 | :rtype: bool
6 | """
7 | left, right = 0, num
8 | while left <= right:
9 | mid = (left+right) / 2
10 | if mid ** 2 == num:
11 | return True
12 | elif mid ** 2 < num:
13 | left = mid + 1
14 | else:
15 | right = mid -1
16 | return False
17 |
--------------------------------------------------------------------------------
/400/380.py:
--------------------------------------------------------------------------------
1 | class RandomizedSet(object):
2 | def __init__(self):
3 | """
4 | Initialize your data structure here.
5 | """
6 | self.data = {}
7 | self.arr = []
8 | self.length = 0
9 |
10 | def insert(self, val):
11 | """
12 | Inserts a value to the set. Returns true if the set did not already contain the specified element.
13 | :type val: int
14 | :rtype: bool
15 | """
16 | if val in self.data:
17 | return False
18 | self.arr.append(val)
19 | self.length += 1
20 | self.data[val] = self.length - 1
21 | return True
22 |
23 | def remove(self, val):
24 | """
25 | Removes a value from the set. Returns true if the set contained the specified element.
26 | :type val: int
27 | :rtype: bool
28 | """
29 | if val in self.data:
30 | last = self.arr.pop()
31 | self.length -= 1
32 | if val != last:
33 | self.arr[self.data[val]] = last
34 | self.data[last] = self.data[val]
35 | del self.data[val]
36 | return True
37 | return False
38 |
39 | def getRandom(self):
40 | """
41 | Get a random element from the set.
42 | :rtype: int
43 | """
44 | import random
45 | if self.length:
46 | return self.arr[random.randrange(self.length)]
47 |
--------------------------------------------------------------------------------
/400/382.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution(object):
8 | def __init__(self, head):
9 | """
10 | @param head The linked list's head.
11 | Note that the head is guaranteed to be not null, so it contains at least one node.
12 | :type head: ListNode
13 | """
14 | self.head = head
15 | self.length = self.get_length()
16 |
17 | def get_length(self):
18 | length, head = 0, self.head
19 | while head:
20 | length += 1
21 | head = head.next
22 | return length
23 |
24 | def getRandom(self):
25 | """
26 | Returns a random node's value.
27 | :rtype: int
28 | """
29 | import random
30 | num = random.choice(range(0, self.length))
31 | head = self.head
32 | while num:
33 | head = head.next
34 | num -= 1
35 | return head.val
36 |
37 | # Your Solution object will be instantiated and called as such:
38 | # obj = Solution(head)
39 | # param_1 = obj.getRandom()
40 | # -*- coding: utf-8 -*-
41 |
--------------------------------------------------------------------------------
/400/383.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def canConstruct(self, ransomNote, magazine):
3 | """
4 | :type ransomNote: str
5 | :type magazine: str
6 | :rtype: bool
7 | """
8 | chars = {}
9 | for m in magazine:
10 | chars[m] = chars.get(m, 0) + 1
11 | for r in ransomNote:
12 | if chars.get(r, -1) > 0:
13 | chars[r] -= 1
14 | else:
15 | return False
16 | return True
17 |
--------------------------------------------------------------------------------
/400/387.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def firstUniqChar(self, s):
3 | """
4 | :type s: str
5 | :rtype: int
6 | """
7 | chars, index = {}, {}
8 | for k, v in enumerate(s):
9 | chars[v] = chars.get(v, 0) + 1
10 | index[v] = index.get(v) or k
11 | first = float('inf')
12 | for c in chars.keys():
13 | if chars[c] == 1:
14 | first = min(index[c], first)
15 | return first if first < float('inf') else -1
16 |
17 |
--------------------------------------------------------------------------------
/400/389.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def findTheDifference(self, s, t):
3 | """
4 | :type s: str
5 | :type t: str
6 | :rtype: str
7 | """
8 | chars = dict()
9 | for c in s:
10 | chars[c] = chars.get(c, 0) + 1
11 | ret = list()
12 | for c in t:
13 | if chars.get(c):
14 | chars[c] -= 1
15 | else:
16 | ret.append(c)
17 | return ''.join(ret)
18 |
--------------------------------------------------------------------------------
/400/392.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def isSubsequence(self, s, t):
3 | """
4 | :type s: str
5 | :type t: str
6 | :rtype: bool
7 | """
8 | loc = 0
9 | for i in s:
10 | loc = t.find(i, loc) + 1
11 | if loc == 0:
12 | return False
13 | return True
14 |
--------------------------------------------------------------------------------
/400/394.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def decodeString(self, s):
3 | """
4 | :type s: str
5 | :rtype: str
6 | """
7 | nums, chars = [], []
8 | i, length = 0, len(s)
9 | while i < length:
10 | j = i + 1
11 | if s[i].isdigit():
12 | num = int(s[i])
13 | while j < length:
14 | if s[j].isdigit():
15 | num = num * 10 + int(s[j])
16 | j += 1
17 | else:
18 | break
19 | nums.append(num)
20 | elif s[i] == '[' or s[i].isalpha():
21 | chars.append(s[i])
22 | else:
23 | t, tmpc = chars.pop(), []
24 | while t != '[':
25 | tmpc.append(t)
26 | t = chars.pop()
27 | tchars = nums.pop() * ''.join(tmpc[::-1])
28 | chars.append(tchars)
29 | i = j
30 | return ''.join(chars)
31 |
--------------------------------------------------------------------------------
/400/400.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def findNthDigit(self, n):
3 | """
4 | :type n: int
5 | :rtype: int
6 | """
7 | digit = 0
8 | for d in range(1, 10):
9 | if d * 9 * (10 ** (d - 1)) >= n:
10 | digit = d
11 | break
12 | num = 0
13 | for d in range(1, digit + 1):
14 | num += int(9 * (d - 1) * 10 ** (d - 2))
15 | ret = (n - num - 1) / digit + 10 ** (digit-1)
16 | return int(str(ret)[(n - num - 1) % digit])
17 |
--------------------------------------------------------------------------------
/400/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 350-400
2 |
3 | 367 [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/description/)
4 | ```Python
5 | class Solution(object):
6 | def isPerfectSquare(self, num):
7 | """
8 | :type num: int
9 | :rtype: bool
10 | """
11 | left, right = 0, num
12 | while left <= right:
13 | mid = (left+right) / 2
14 | if mid ** 2 == num:
15 | return True
16 | elif mid ** 2 < num:
17 | left = mid + 1
18 | else:
19 | right = mid -1
20 | return False
21 | ```
22 |
23 | 380 [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/description/)
24 | ```python
25 | class RandomizedSet(object):
26 |
27 | def __init__(self):
28 | """
29 | Initialize your data structure here.
30 | """
31 | self.data = {}
32 | self.arr = []
33 | self.length = 0
34 |
35 |
36 | def insert(self, val):
37 | """
38 | Inserts a value to the set. Returns true if the set did not already contain the specified element.
39 | :type val: int
40 | :rtype: bool
41 | """
42 | if val in self.data:
43 | return False
44 | self.arr.append(val)
45 | self.length += 1
46 | self.data[val] = self.length - 1
47 | return True
48 |
49 | def remove(self, val):
50 | """
51 | Removes a value from the set. Returns true if the set contained the specified element.
52 | :type val: int
53 | :rtype: bool
54 | """
55 | if val in self.data:
56 | last = self.arr.pop()
57 | self.length -= 1
58 | if val != last:
59 | self.arr[self.data[val]] = last
60 | self.data[last] = self.data[val]
61 | del self.data[val]
62 | return True
63 | return False
64 |
65 | def getRandom(self):
66 | """
67 | Get a random element from the set.
68 | :rtype: int
69 | """
70 | import random
71 | if self.length:
72 | return self.arr[random.randrange(self.length)]
73 | ```
74 |
75 | 382 [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/description/)
76 | ```python
77 | class Solution(object):
78 | def __init__(self, head):
79 | """
80 | @param head The linked list's head.
81 | Note that the head is guaranteed to be not null, so it contains at least one node.
82 | :type head: ListNode
83 | """
84 | self.head = head
85 | self.length = self.get_length()
86 |
87 | def get_length(self):
88 | length, head = 0, self.head
89 | while head:
90 | length += 1
91 | head = head.next
92 | return length
93 |
94 | def getRandom(self):
95 | """
96 | Returns a random node's value.
97 | :rtype: int
98 | """
99 | import random
100 | num = random.choice(range(0, self.length))
101 | head = self.head
102 | while num:
103 | head = head.next
104 | num -= 1
105 | return head.val
106 | ```
107 |
108 | 383 [Ransom Note](https://leetcode.com/problems/ransom-note/description/)
109 | ```python
110 | class Solution(object):
111 | def canConstruct(self, ransomNote, magazine):
112 | """
113 | :type ransomNote: str
114 | :type magazine: str
115 | :rtype: bool
116 | """
117 | chars = {}
118 | for m in magazine:
119 | chars[m] = chars.get(m, 0) + 1
120 | for r in ransomNote:
121 | if chars.get(r, -1) > 0:
122 | chars[r] -= 1
123 | else:
124 | return False
125 | return True
126 | ```
127 |
128 | 387 [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/description/)
129 | ```python
130 | class Solution(object):
131 | def firstUniqChar(self, s):
132 | """
133 | :type s: str
134 | :rtype: int
135 | """
136 | chars, index = {}, {}
137 | for k, v in enumerate(s):
138 | chars[v] = chars.get(v, 0) + 1
139 | index[v] = index.get(v) or k
140 | first = float('inf')
141 | for c in chars.keys():
142 | if chars[c] == 1:
143 | first = min(index[c], first)
144 | return first if first < float('inf') else -1
145 | ```
146 |
147 | 389 [Find the Difference](https://leetcode.com/problems/find-the-difference/description/)
148 | ```python
149 | class Solution(object):
150 | def findTheDifference(self, s, t):
151 | """
152 | :type s: str
153 | :type t: str
154 | :rtype: str
155 | """
156 | chars = dict()
157 | for c in s:
158 | chars[c] = chars.get(c, 0) + 1
159 | ret = list()
160 | for c in t:
161 | if chars.get(c):
162 | chars[c] -= 1
163 | else:
164 | ret.append(c)
165 | return ''.join(ret)
166 | ```
167 |
168 | 392 [Is Subsequence](https://leetcode.com/problems/is-subsequence/description/)
169 | ```python
170 | class Solution(object):
171 | def isSubsequence(self, s, t):
172 | """
173 | :type s: str
174 | :type t: str
175 | :rtype: bool
176 | """
177 | loc = 0
178 | for i in s:
179 | loc = t.find(i, loc) + 1
180 | if loc == 0:
181 | return False
182 | return True
183 | ```
184 |
185 | 394 [Decode String](https://leetcode.com/problems/decode-string/description/) (30ms beat 98%)
186 | ```python
187 | class Solution(object):
188 | def decodeString(self, s):
189 | """
190 | :type s: str
191 | :rtype: str
192 | """
193 | nums, chars = [], []
194 | i, length = 0, len(s)
195 | while i < length:
196 | j = i + 1
197 | if s[i].isdigit():
198 | num = int(s[i])
199 | while j < length:
200 | if s[j].isdigit():
201 | num = num * 10 + int(s[j])
202 | j += 1
203 | else:
204 | break
205 | nums.append(num)
206 | elif s[i] == '[' or s[i].isalpha():
207 | chars.append(s[i])
208 | else:
209 | t, tmpc = chars.pop(), []
210 | while t != '[':
211 | tmpc.append(t)
212 | t = chars.pop()
213 | tchars = nums.pop() * ''.join(tmpc[::-1])
214 | chars.append(tchars)
215 | i = j
216 | return ''.join(chars)
217 | ```
218 |
219 | 400 [Nth Digit](https://leetcode.com/problems/nth-digit/description/)
220 | ```python
221 | class Solution(object):
222 | def findNthDigit(self, n):
223 | """
224 | :type n: int
225 | :rtype: int
226 | """
227 | digit = 0
228 | for d in range(1, 10):
229 | if d * 9 * (10 ** (d - 1)) >= n:
230 | digit = d
231 | break
232 | num = 0
233 | for d in range(1, digit + 1):
234 | num += int(9 * (d - 1) * 10 ** (d - 2))
235 | ret = (n - num - 1) / digit + 10 ** (digit-1)
236 | return int(str(ret)[(n - num - 1) % digit])
237 | ```
238 |
239 |
--------------------------------------------------------------------------------
/450/404.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def sumOfLeftLeaves(self, root):
10 | """
11 | :type root: TreeNode
12 | :rtype: int
13 | """
14 | if not root:
15 | return 0
16 | return self.sum_of_left(root.left, True) + self.sum_of_left(root.right, False)
17 |
18 | def sum_of_left(self, root, is_left):
19 | if not root:
20 | return 0
21 | if root and not root.left and not root.right:
22 | return root.val if is_left else 0
23 | return self.sum_of_left(root.left, True) + self.sum_of_left(root.right, False)
24 |
25 |
--------------------------------------------------------------------------------
/450/409.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def longestPalindrome(self, s):
3 | """
4 | :type s: str
5 | :rtype: int
6 | """
7 | sdict = {}
8 | for c in s:
9 | sdict[c] = sdict.get(c, 0) + 1
10 | ret, remain = 0, 0
11 | for k in sdict.keys():
12 | if sdict[k] % 2 == 0:
13 | ret += sdict[k]
14 | else:
15 | ret += (sdict[k] - 1)
16 | remain = 1
17 | return ret + remain
18 |
--------------------------------------------------------------------------------
/450/412.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def fizzBuzz(self, n):
3 | """
4 | :type n: int
5 | :rtype: List[str]
6 | """
7 | return [(not i % 3)*'Fizz' + (not i % 5)*'Buzz' or str(i) for i in range(1, n+1)]
8 |
--------------------------------------------------------------------------------
/450/414.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def thirdMax(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: int
6 | """
7 | nums = set(nums)
8 | a = b = c = float('-inf')
9 | for n in nums:
10 | if n > a:
11 | b, c, a = a, b, n
12 | elif a > n > b:
13 | c, b = b, n
14 | elif b > n > c:
15 | c = n
16 | return c if len(nums) >= 3 else a
17 |
--------------------------------------------------------------------------------
/450/415.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def addStrings(self, num1, num2):
3 | """
4 | :type num1: str
5 | :type num2: str
6 | :rtype: str
7 | """
8 | min_len = len(num1) if len(num1) < len(num2) else len(num2)
9 | max_len = len(num1) if len(num1) > len(num2) else len(num2)
10 | ret, carry, digit = '', 0, -1
11 | if len(num1) <= len(num2):
12 | num1 = '0' * (max_len - min_len) + num1
13 | else:
14 | num2 = '0' * (max_len - min_len) + num2
15 | while digit >= -max_len:
16 | n1 = ord(num1[digit]) - ord('0')
17 | n2 = ord(num2[digit]) - ord('0')
18 | ret += str((n1 + n2 + carry) % 10)
19 | carry = (n1 + n2 + carry) / 10
20 | digit -= 1
21 | if carry != 0:
22 | ret += str(carry)
23 | return ret[::-1]
24 |
--------------------------------------------------------------------------------
/450/434.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def countSegments(self, s):
3 | """
4 | :type s: str
5 | :rtype: int
6 | """
7 | return len(s.split())
8 |
--------------------------------------------------------------------------------
/450/441.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def arrangeCoins(self, n):
3 | """
4 | :type n: int
5 | :rtype: int
6 | """
7 | return int(((2 + 8*n) ** 0.5 - 1) / 2)
8 |
--------------------------------------------------------------------------------
/450/442.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def findDuplicates(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: List[int]
6 | """
7 | ret = []
8 | for n in nums:
9 | if nums[abs(n)-1] < 0:
10 | ret.append(abs(n))
11 | else:
12 | nums[abs(n) - 1] = -nums[abs(n) - 1]
13 | return ret
14 |
15 |
--------------------------------------------------------------------------------
/450/445.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution(object):
8 | def addTwoNumbers(self, l1, l2):
9 | """
10 | :type l1: ListNode
11 | :type l2: ListNode
12 | :rtype: ListNode
13 | """
14 | from collections import deque
15 | l1_vals, l2_vals = deque(), deque()
16 | while l1 and l2:
17 | l1_vals.append(l1.val)
18 | l2_vals.append(l2.val)
19 | l1, l2 = l1.next, l2.next
20 | while l1:
21 | l1_vals.append(l1.val)
22 | l1 = l1.next
23 | while l2:
24 | l2_vals.append(l2.val)
25 | l2 = l2.next
26 | ret, carry = deque(), 0
27 | while l1_vals and l2_vals:
28 | val = l1_vals.pop() + l2_vals.pop() + carry
29 | ret.append(ListNode(val % 10))
30 | carry = val / 10
31 | while l1_vals:
32 | val = l1_vals.pop() + carry
33 | ret.append(ListNode(val % 10))
34 | carry = val / 10
35 | while l2_vals:
36 | val = l2_vals.pop() + carry
37 | ret.append(ListNode(val % 10))
38 | carry = val / 10
39 | h = head = ListNode(0)
40 | if carry:
41 | h.next, h = ListNode(carry), h.next
42 | while ret:
43 | h.next = ret.pop()
44 | h = h.next
45 | return head.next
46 |
--------------------------------------------------------------------------------
/450/448.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def findDisappearedNumbers(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: List[int]
6 | """
7 | for n in nums:
8 | t = abs(n) - 1
9 | nums[t] = -abs(nums[t])
10 | return [k + 1 for k, v in enumerate(nums) if v > 0]
11 |
12 |
--------------------------------------------------------------------------------
/450/450.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def deleteNode(self, root, key):
10 | """
11 | :type root: TreeNode
12 | :type key: int
13 | :rtype: TreeNode
14 | """
15 | if not root:
16 | return None
17 | if root.val == key:
18 | left, right = root.left, root.right
19 | root = left
20 | while left and left.right:
21 | left = left.right
22 | if left:
23 | left.right = right
24 | else:
25 | root = right
26 | elif root.val > key:
27 | root.left = self.deleteNode(root.left, key)
28 | else:
29 | root.right = self.deleteNode(root.right, key)
30 | return root
31 |
--------------------------------------------------------------------------------
/450/README.md:
--------------------------------------------------------------------------------
1 | # LeegtCode 401-450
2 |
3 | 404 [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/description/)
4 | ```python
5 | class Solution(object):
6 | def sumOfLeftLeaves(self, root):
7 | """
8 | :type root: TreeNode
9 | :rtype: int
10 | """
11 | if not root:
12 | return 0
13 | return self.sum_of_left(root.left, True) + self.sum_of_left(root.right, False)
14 |
15 | def sum_of_left(self, root, is_left):
16 | if not root:
17 | return 0
18 | if root and not root.left and not root.right:
19 | return root.val if is_left else 0
20 | return self.sum_of_left(root.left, True) + self.sum_of_left(root.right, False)
21 | ```
22 |
23 | 409 [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/description/)
24 | ```python
25 | class Solution(object):
26 | def longestPalindrome(self, s):
27 | """
28 | :type s: str
29 | :rtype: int
30 | """
31 | sdict = {}
32 | for c in s:
33 | sdict[c] = sdict.get(c, 0) + 1
34 | ret, remain = 0, 0
35 | for k in sdict.keys():
36 | if sdict[k] % 2 == 0:
37 | ret += sdict[k]
38 | else:
39 | ret += (sdict[k] - 1)
40 | remain = 1
41 | return ret + remain
42 | ```
43 |
44 | 412 [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/description/)
45 | ```python
46 | class Solution(object):
47 | def fizzBuzz(self, n):
48 | """
49 | :type n: int
50 | :rtype: List[str]
51 | """
52 | return [(not i % 3)*'Fizz' + (not i % 5)*'Buzz' or str(i) for i in range(1, n+1)]
53 | ```
54 |
55 | 414 [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/description/)
56 | 415 [Add Strings](https://leetcode.com/problems/add-strings/description/)
57 | ```python
58 | class Solution(object):
59 | def addStrings(self, num1, num2):
60 | """
61 | :type num1: str
62 | :type num2: str
63 | :rtype: str
64 | """
65 | min_len = len(num1) if len(num1) < len(num2) else len(num2)
66 | max_len = len(num1) if len(num1) > len(num2) else len(num2)
67 | ret, carry, digit = '', 0, -1
68 | if len(num1) <= len(num2):
69 | num1 = '0' * (max_len - min_len) + num1
70 | else:
71 | num2 = '0' * (max_len - min_len) + num2
72 | while digit >= -max_len:
73 | n1 = ord(num1[digit]) - ord('0')
74 | n2 = ord(num2[digit]) - ord('0')
75 | ret += str((n1 + n2 + carry) % 10)
76 | carry = (n1 + n2 + carry) / 10
77 | digit -= 1
78 | if carry != 0:
79 | ret += str(carry)
80 | return ret[::-1]
81 | ```
82 |
83 | 434 [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/description/)
84 | ```python
85 | class Solution(object):
86 | def countSegments(self, s):
87 | """
88 | :type s: str
89 | :rtype: int
90 | """
91 | return len(s.split())
92 | ```
93 |
94 | 441 [Arranging Coins](https://leetcode.com/problems/arranging-coins/description/)
95 | ```python
96 | class Solution(object):
97 | def arrangeCoins(self, n):
98 | """
99 | :type n: int
100 | :rtype: int
101 | """
102 | return int(((2 + 8*n) ** 0.5 - 1) / 2)
103 | ```
104 |
105 | 442 [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/description/)
106 | ```python
107 | class Solution(object):
108 | def findDuplicates(self, nums):
109 | """
110 | :type nums: List[int]
111 | :rtype: List[int]
112 | """
113 | ret = []
114 | for n in nums:
115 | if nums[abs(n)-1] < 0:
116 | ret.append(abs(n))
117 | else:
118 | nums[abs(n) - 1] = -nums[abs(n) - 1]
119 | return ret
120 | ```
121 |
122 | 445 [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/description/)
123 | ```python
124 | # Definition for singly-linked list.
125 | # class ListNode(object):
126 | # def __init__(self, x):
127 | # self.val = x
128 | # self.next = None
129 |
130 | class Solution(object):
131 | def addTwoNumbers(self, l1, l2):
132 | """
133 | :type l1: ListNode
134 | :type l2: ListNode
135 | :rtype: ListNode
136 | """
137 | from collections import deque
138 | l1_vals, l2_vals = deque(), deque()
139 | while l1 and l2:
140 | l1_vals.append(l1.val)
141 | l2_vals.append(l2.val)
142 | l1, l2 = l1.next, l2.next
143 | while l1:
144 | l1_vals.append(l1.val)
145 | l1 = l1.next
146 | while l2:
147 | l2_vals.append(l2.val)
148 | l2 = l2.next
149 | ret, carry = deque(), 0
150 | while l1_vals and l2_vals:
151 | val = l1_vals.pop() + l2_vals.pop() + carry
152 | ret.append(ListNode(val % 10))
153 | carry = val / 10
154 | while l1_vals:
155 | val = l1_vals.pop() + carry
156 | ret.append(ListNode(val % 10))
157 | carry = val / 10
158 | while l2_vals:
159 | val = l2_vals.pop() + carry
160 | ret.append(ListNode(val % 10))
161 | carry = val / 10
162 | h = head = ListNode(0)
163 | if carry:
164 | h.next, h = ListNode(carry), h.next
165 | while ret:
166 | h.next = ret.pop()
167 | h = h.next
168 | return head.next
169 | ```
170 |
171 | 448 [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/)
172 | ```python
173 | class Solution(object):
174 | def findDisappearedNumbers(self, nums):
175 | """
176 | :type nums: List[int]
177 | :rtype: List[int]
178 | """
179 | for n in nums:
180 | t = abs(n) - 1
181 | nums[t] = -abs(nums[t])
182 | return [k + 1 for k, v in enumerate(nums) if v > 0]
183 | ```
184 |
185 | 450 [Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/description/)
186 | ```python
187 | class Solution(object):
188 | def deleteNode(self, root, key):
189 | """
190 | :type root: TreeNode
191 | :type key: int
192 | :rtype: TreeNode
193 | """
194 | if not root:
195 | return None
196 | if root.val == key:
197 | left, right = root.left, root.right
198 | root = left
199 | while left and left.right:
200 | left = left.right
201 | if left:
202 | left.right = right
203 | else:
204 | root = right
205 | elif root.val > key:
206 | root.left = self.deleteNode(root.left, key)
207 | else:
208 | root.right = self.deleteNode(root.right, key)
209 | return root
210 | ```
211 |
--------------------------------------------------------------------------------
/50/1.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def twoSum(self, nums, target):
3 | """
4 | :type nums: List[int]
5 | :type target: int
6 | :rtype: List[int]
7 | """
8 | dicts = {}
9 | for k, v in enumerate(nums):
10 | if target - v in dicts:
11 | return [dicts.get(target-v), k]
12 | dicts[v] = k
13 |
--------------------------------------------------------------------------------
/50/11.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def maxArea(self, height):
3 | """
4 | :type height: List[int]
5 | :rtype: int
6 | """
7 | left, right = 0, len(height) - 1
8 | water = (right - left) * (height[left] if height[left] <= height[right] else height[right])
9 | while left < right:
10 | if height[left] <= height[right]:
11 | left += 1
12 | else:
13 | right -= 1
14 | cur = (right - left) * (height[left] if height[left] <= height[right] else height[right])
15 | water = cur if cur > water else water
16 | return water
17 |
18 |
--------------------------------------------------------------------------------
/50/14.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def longestCommonPrefix(self, strs):
3 | """
4 | :type strs: List[str]
5 | :rtype: str
6 | """
7 | if not strs:
8 | return ''
9 | pre = strs[0]
10 | for s in strs:
11 | len_pre = len(pre)
12 | while s[0:len_pre] != pre:
13 | len_pre -= 1
14 | pre = pre[0:len_pre]
15 | if not pre:
16 | return pre
17 | return pre
18 |
--------------------------------------------------------------------------------
/50/19.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution(object):
8 | def removeNthFromEnd(self, head, n):
9 | """
10 | :type head: ListNode
11 | :type n: int
12 | :rtype: ListNode
13 | """
14 | stack = []
15 | move = head
16 | while move:
17 | stack.append(move)
18 | move = move.next
19 | if len(stack) == n:
20 | return head.next
21 | if n == 1:
22 | stack[-n-1].next = None
23 | else:
24 | stack[-n-1].next = stack[-n+1]
25 | stack[-n].next = None
26 | return head
27 |
--------------------------------------------------------------------------------
/50/2.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution(object):
8 | def addTwoNumbers(self, l1, l2):
9 | """
10 | :type l1: ListNode
11 | :type l2: ListNode
12 | :rtype: ListNode
13 | """
14 | head = move = ListNode(0)
15 | carry = 0
16 | while l1 or l2 or carry:
17 | if l1:
18 | carry += l1.val
19 | l1 = l1.next
20 | if l2:
21 | carry += l2.val
22 | l2 = l2.next
23 | move.next = ListNode(carry % 10)
24 | carry /= 10
25 | move = move.next
26 | return head.next
--------------------------------------------------------------------------------
/50/20.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def isValid(self, s):
3 | """
4 | :type s: str
5 | :rtype: bool
6 | """
7 | left = ['(', '[', '{']
8 | stack = []
9 | for c in s:
10 | if c in left:
11 | stack.append(c)
12 | elif c == ')':
13 | if stack and stack[-1] == '(':
14 | stack.pop()
15 | else:
16 | return False
17 | elif c == ']':
18 | if stack and stack[-1] == '[':
19 | stack.pop()
20 | else:
21 | return False
22 | else:
23 | if stack and stack[-1] == '{':
24 | stack.pop()
25 | else:
26 | return False
27 | return len(stack) == 0
28 |
--------------------------------------------------------------------------------
/50/21.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution(object):
8 | def mergeTwoLists(self, l1, l2):
9 | """
10 | :type l1: ListNode
11 | :type l2: ListNode
12 | :rtype: ListNode
13 | """
14 | pre = ret = ListNode(0)
15 | while l1 and l2:
16 | if l1.val <= l2.val:
17 | pre.next = l1
18 | l1 = l1.next
19 | else:
20 | pre.next = l2
21 | l2 = l2.next
22 | pre = pre.next
23 | while l1:
24 | pre.next = l1
25 | l1 = l1.next
26 | pre = pre.next
27 | while l2:
28 | pre.next = l2
29 | l2, pre = l2.next, pre.next
30 | return ret.next
31 |
--------------------------------------------------------------------------------
/50/23.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution(object):
8 | def mergeKLists(self, lists):
9 | """
10 | :type lists: List[ListNode]
11 | :rtype: ListNode
12 | """
13 | import heapq
14 | min_heap = []
15 | ret = head = ListNode(0)
16 | for k, link in enumerate(lists):
17 | if link:
18 | heapq.heappush(min_heap, [link.val, link])
19 | while min_heap:
20 | cur = heapq.heappop(min_heap)
21 | ret.next = cur[-1]
22 | ret = ret.next
23 | if ret.next:
24 | heapq.heappush(min_heap, [ret.next.val, ret.next])
25 | return head.next
26 |
--------------------------------------------------------------------------------
/50/24.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def swapPairs(self, head):
3 | """
4 | :type head: ListNode
5 | :rtype: ListNode
6 | """
7 | pre = m_pre = ListNode(0)
8 | pre.next = head
9 | while head and head.next:
10 | hn = head.next
11 | hnn = hn.next
12 | pre.next, hn.next, head.next = hn, head, hnn
13 | pre, head = head, hnn
14 | return m_pre.next
15 |
--------------------------------------------------------------------------------
/50/25.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution(object):
8 | def reverseKGroup(self, head, k):
9 | """
10 | :type head: ListNode
11 | :type k: int
12 | :rtype: ListNode
13 | """
14 | move, count = head, 0
15 | while move:
16 | count += 1
17 | move = move.next
18 | if count < k:
19 | return head
20 | move, current_count, current_last = head, 0, head
21 | move_pre = None
22 | while current_count < k:
23 | m_next = move.next
24 | move.next, move_pre = move_pre, move
25 | move = m_next
26 | current_count += 1
27 | current_last.next = self.reverseKGroup(move, k)
28 | return move_pre
29 |
--------------------------------------------------------------------------------
/50/26.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def removeDuplicates(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: int
6 | """
7 | left = ret = 0
8 | cur = None
9 | while left < len(nums):
10 | if nums[left] != cur:
11 | nums[ret] = nums[left]
12 | ret += 1
13 | cur = nums[left]
14 | left += 1
15 | return ret
16 |
17 |
--------------------------------------------------------------------------------
/50/27.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def removeElement(self, nums, val):
3 | """
4 | :type nums: List[int]
5 | :type val: int
6 | :rtype: int
7 | """
8 | left, right = 0, len(nums) - 1
9 | while left <= right:
10 | if nums[left] == val:
11 | nums[left], nums[right] = nums[right], nums[left]
12 | right -= 1
13 | else:
14 | left += 1
15 | return left
16 |
17 |
--------------------------------------------------------------------------------
/50/28.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def strStr(self, haystack, needle):
3 | """
4 | :type haystack: str
5 | :type needle: str
6 | :rtype: int
7 | """
8 | return haystack.find(needle)
9 |
10 |
--------------------------------------------------------------------------------
/50/3.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def lengthOfLongestSubstring(self, s):
3 | """
4 | :type s: str
5 | :rtype: int
6 | """
7 | hashes = {}
8 | left, right, length = 0, 0, len(s)
9 | max_len = 0
10 | while right < length:
11 | if hashes.get(s[right]) and hashes[s[right]] >= left:
12 | left = hashes[s[right]]
13 | hashes[s[right]] = right + 1
14 | max_len = max(max_len, right - left + 1)
15 | right += 1
16 | return max_len
17 |
--------------------------------------------------------------------------------
/50/33.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 |
3 | def find_min(self, nums):
4 | if not nums:
5 | return -1
6 | left, right = 0, len(nums) - 1
7 | while nums[left] > nums[right]:
8 | if right - left == 1:
9 | return right
10 | mid = (left + right) / 2
11 | if nums[left] <= nums[mid]:
12 | left = mid
13 | if nums[right] >= nums[mid]:
14 | right = mid
15 | return 0
16 |
17 | def search(self, nums, target):
18 | """
19 | :type nums: List[int]
20 | :type target: int
21 | :rtype: int
22 | """
23 | if not nums:
24 | return -1
25 | min_index = self.find_min(nums)
26 | if nums[min_index] == target:
27 | return min_index
28 | elif nums[min_index] > target:
29 | return -1
30 | else:
31 | left = self.search_t(nums, 0, min_index, target)
32 | right = self.search_t(nums, min_index, len(nums)-1, target)
33 | if left >= 0:
34 | return left
35 | if right >= 0:
36 | return right
37 | return -1
38 |
39 | def search_t(self, nums, left, right, target):
40 | while left <= right:
41 | mid = (left + right) / 2
42 | if nums[mid] == target:
43 | return mid
44 | elif nums[mid] < target:
45 | left = mid + 1
46 | else:
47 | right = mid - 1
48 | return -1
49 |
--------------------------------------------------------------------------------
/50/34.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def searchRange(self, nums, target):
3 | """
4 | :type nums: List[int]
5 | :type target: int
6 | :rtype: List[int]
7 | """
8 | return [self.search_left(nums, target), self.search_right(nums, target)]
9 |
10 | def search_left(self, nums, target):
11 | left, right = 0, len(nums) - 1
12 | while left <= right:
13 | mid = (left + right) / 2
14 | if nums[mid] == target:
15 | if mid == 0 or nums[mid-1] < target:
16 | return mid
17 | right = mid - 1
18 | elif nums[mid] < target:
19 | left = mid + 1
20 | else:
21 | right = mid - 1
22 | return -1
23 |
24 | def search_right(self, nums, target):
25 | left, right = 0, len(nums) - 1
26 | while left <= right:
27 | mid = (left + right) / 2
28 | if nums[mid] == target:
29 | if mid == len(nums) - 1 or nums[mid+1] > target:
30 | return mid
31 | left = mid + 1
32 | elif nums[mid] < target:
33 | left = mid + 1
34 | else:
35 | right = mid - 1
36 | return -1
37 |
38 |
--------------------------------------------------------------------------------
/50/35.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def searchInsert(self, nums, target):
3 | """
4 | :type nums: List[int]
5 | :type target: int
6 | :rtype: int
7 | """
8 | left, right = 0, len(nums) - 1
9 | mid = (left + right) / 2
10 | while left <= right:
11 | if nums[mid] == target:
12 | return mid
13 | elif nums[mid] > target:
14 | right = mid - 1
15 | else:
16 | left = mid + 1
17 | mid = (left + right) / 2
18 | if nums[mid] > target:
19 | return mid - 1 if mid > 0 else 0
20 | return mid + 1
21 |
--------------------------------------------------------------------------------
/50/38.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def countAndSay(self, n):
3 | """
4 | :type n: int
5 | :rtype: str
6 | """
7 | start = '1'
8 | for i in range(n-1):
9 | c = start[0]
10 | nums = 0
11 | tmp = []
12 | for s in start:
13 | if s == c:
14 | nums += 1
15 | else:
16 | tmp.append([nums, c])
17 | nums = 1
18 | c = s
19 | tmp.append([nums, c])
20 | start = ''.join([str(d[0])+d[1] for d in tmp])
21 | return start
22 |
--------------------------------------------------------------------------------
/50/46.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def permute(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: List[List[int]]
6 | """
7 | from itertools import permutations
8 | return list(permutations(nums))
9 |
10 |
--------------------------------------------------------------------------------
/50/47.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def permuteUnique(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: List[List[int]]
6 | """
7 | from itertools import permutations
8 | return list(set(permutations(nums)))
9 |
10 |
--------------------------------------------------------------------------------
/50/48.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def rotate(self, matrix):
3 | """
4 | :type matrix: List[List[int]]
5 | :rtype: void Do not return anything, modify matrix in-place instead.
6 | """
7 | n = len(matrix)
8 | m = 0
9 | while m <= n / 2:
10 | k = m
11 | while k < n - 1 - m:
12 | matrix[m][k], matrix[k][n-1-m], matrix[n-1-m][n-1-k], matrix[n-1-k][m] = \
13 | matrix[n-1-k][m], matrix[m][k], matrix[k][n-1-m], matrix[n-1-m][n-1-k]
14 | k += 1
15 | m += 1
16 |
--------------------------------------------------------------------------------
/50/49.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def groupAnagrams(self, strs):
3 | """
4 | :type strs: List[str]
5 | :rtype: List[List[str]]
6 | """
7 | ret = {}
8 | for s in strs:
9 | ts = ''.join(sorted(s))
10 | if ret.get(ts):
11 | ret[ts].append(s)
12 | else:
13 | ret[ts] = [s]
14 | return ret.values()
15 |
16 |
--------------------------------------------------------------------------------
/50/50.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def myPow(self, x, n):
3 | """
4 | :type x: float
5 | :type n: int
6 | :rtype: float
7 | """
8 | return x ** n
9 |
10 |
--------------------------------------------------------------------------------
/50/6.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def convert(self, s, numRows):
3 | """
4 | :type s: str
5 | :type numRows: int
6 | :rtype: str
7 | """
8 | rows = [[] for _ in range(numRows)]
9 | move, counts = 0, 0
10 |
11 | for c in s:
12 | if move == 0:
13 | rows[counts].append(c)
14 | counts += 1
15 | if counts == numRows:
16 | move = 1
17 | counts -= 2
18 | else:
19 | rows[counts].append(c)
20 | counts -= 1
21 | if counts < 0:
22 | move = 0
23 | counts += 2
24 | return ''.join([''.join(r) for r in rows])
25 |
--------------------------------------------------------------------------------
/50/7.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def reverse(self, x):
3 | """
4 | :type x: int
5 | :rtype: int
6 | """
7 | ret = 0
8 | t = abs(x)
9 | while t:
10 | ret = 10 * ret + t % 10
11 | t /= 10
12 | if ret > 2 ** 31 or -ret < -2 ** 31:
13 | return 0
14 | return ret if x >= 0 else -ret
15 |
--------------------------------------------------------------------------------
/50/8.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def myAtoi(self, str):
3 | """
4 | :type str: str
5 | :rtype: int
6 | """
7 | s = ''
8 | for i in str.strip():
9 | if i == '-' or i == '+' or i.isdigit():
10 | if '-' not in s or '+' not in s:
11 | s += i
12 | else:
13 | break
14 | try:
15 | ret = int(s)
16 | if ret >= -2147483648 and ret <= 2147483647:
17 | return ret
18 | elif ret < -2147483648:
19 | return -2147483648
20 | elif ret > 2147483647:
21 | return 2147483647
22 | else:
23 | return 0
24 | except:
25 | return 0
26 |
--------------------------------------------------------------------------------
/50/9.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def isPalindrome(self, x):
3 | """
4 | :type x: int
5 | :rtype: bool
6 | """
7 | if x < 0:
8 | return False
9 | r = 0
10 | t = x
11 | while t:
12 | r = r * 10 + t % 10
13 | t /= 10
14 | return r == x
15 |
16 |
--------------------------------------------------------------------------------
/50/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 1-50
2 |
3 | 1 [Two Sum](https://leetcode.com/problems/two-sum/description/)
4 | ```python
5 | class Solution(object):
6 | def twoSum(self, nums, target):
7 | """
8 | :type nums: List[int]
9 | :type target: int
10 | :rtype: List[int]
11 | """
12 | dicts = {}
13 | for k, v in enumerate(nums):
14 | if target - v in dicts:
15 | return [dicts.get(target-v), k]
16 | dicts[v] = k
17 | ```
18 |
19 | 2 [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/description/)
20 | ```Python
21 | class Solution(object):
22 | def addTwoNumbers(self, l1, l2):
23 | """
24 | :type l1: ListNode
25 | :type l2: ListNode
26 | :rtype: ListNode
27 | """
28 | a = b = 0
29 | carry = 0
30 | while l1:
31 | a += l1.val * 10 ** carry
32 | carry += 1
33 | l1 = l1.next
34 | carry = 0
35 | while l2:
36 | b += l2.val * 10 ** carry
37 | carry += 1
38 | l2 = l2.next
39 | ret = a + b
40 | h = m = ListNode(0)
41 | if not ret:
42 | return h
43 | while ret:
44 | m.next = ListNode(ret % 10)
45 | ret /= 10
46 | m = m.next
47 | return h.next
48 | ```
49 |
50 | 3 [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/description/)
51 | ```Python
52 | class Solution(object):
53 | def lengthOfLongestSubstring(self, s):
54 | """
55 | :type s: str
56 | :rtype: int
57 | """
58 | hashes = {}
59 | left, right, length = 0, 0, len(s)
60 | max_len = 0
61 | while right < length:
62 | if hashes.get(s[right]) and hashes[s[right]] >= left:
63 | left = hashes[s[right]]
64 | hashes[s[right]] = right + 1
65 | max_len = max(max_len, right - left + 1)
66 | right += 1
67 | return max_len
68 | ```
69 |
70 | 6 [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/description/)
71 | ```python
72 | class Solution(object):
73 | def convert(self, s, numRows):
74 | """
75 | :type s: str
76 | :type numRows: int
77 | :rtype: str
78 | """
79 | rows = [[] for _ in range(numRows)]
80 | move, counts = 0, 0
81 |
82 | for c in s:
83 | if move == 0:
84 | rows[counts].append(c)
85 | counts += 1
86 | if counts == numRows:
87 | move = 1
88 | counts -= 2
89 | else:
90 | rows[counts].append(c)
91 | counts -= 1
92 | if counts < 0:
93 | move = 0
94 | counts += 2
95 | return ''.join([''.join(r) for r in rows])
96 | ```
97 |
98 | 7 [Reverse Integer](https://leetcode.com/problems/reverse-integer/description/)
99 | ```python
100 | class Solution(object):
101 | def reverse(self, x):
102 | """
103 | :type x: int
104 | :rtype: int
105 | """
106 | ret = 0
107 | t = abs(x)
108 | while t:
109 | ret = 10 * ret + t % 10
110 | t /= 10
111 | if ret > 2 ** 31 or -ret < -2 ** 31:
112 | return 0
113 | return ret if x >= 0 else -ret
114 | ```
115 |
116 | 8 [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/description/)
117 | ```python
118 | class Solution(object):
119 | def myAtoi(self, str):
120 | """
121 | :type str: str
122 | :rtype: int
123 | """
124 | s = ''
125 | for i in str.strip():
126 | if i == '-' or i == '+' or i.isdigit():
127 | if '-' not in s or '+' not in s:
128 | s += i
129 | else:
130 | break
131 | try:
132 | ret = int(s)
133 | if ret >= -2147483648 and ret <= 2147483647:
134 | return ret
135 | elif ret < -2147483648:
136 | return -2147483648
137 | elif ret > 2147483647:
138 | return 2147483647
139 | else:
140 | return 0
141 | except:
142 | return 0
143 | ```
144 |
145 | 9 [Palindrome Number](https://leetcode.com/problems/palindrome-number/description/)
146 | ```python
147 | class Solution(object):
148 | def isPalindrome(self, x):
149 | """
150 | :type x: int
151 | :rtype: bool
152 | """
153 | if x < 0:
154 | return False
155 | r = 0
156 | t = x
157 | while t:
158 | r = r * 10 + t % 10
159 | t /= 10
160 | return r == x
161 | ```
162 |
163 | 11 [Container With Most Water](https://leetcode.com/problems/container-with-most-water/description/)
164 | ```python
165 | class Solution(object):
166 | def maxArea(self, height):
167 | """
168 | :type height: List[int]
169 | :rtype: int
170 | """
171 | left, right = 0, len(height) - 1
172 | water = (right - left) * (height[left] if height[left] <= height[right] else height[right])
173 | while left < right:
174 | if height[left] <= height[right]:
175 | left += 1
176 | else:
177 | right -= 1
178 | cur = (right - left) * (height[left] if height[left] <= height[right] else height[right])
179 | water = cur if cur > water else water
180 | return water
181 | ```
182 |
183 | 14 [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/description/)
184 | ```python
185 | class Solution(object):
186 | def longestCommonPrefix(self, strs):
187 | """
188 | :type strs: List[str]
189 | :rtype: str
190 | """
191 | if not strs:
192 | return ''
193 | pre = strs[0]
194 | for s in strs:
195 | len_pre = len(pre)
196 | while s[0:len_pre] != pre:
197 | len_pre -= 1
198 | pre = pre[0:len_pre]
199 | if not pre:
200 | return pre
201 | return pre
202 | ```
203 |
204 | 19 [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/)
205 | ```python
206 | class Solution(object):
207 | def removeNthFromEnd(self, head, n):
208 | """
209 | :type head: ListNode
210 | :type n: int
211 | :rtype: ListNode
212 | """
213 | stack = []
214 | move = head
215 | while move:
216 | stack.append(move)
217 | move = move.next
218 | if len(stack) == n:
219 | return head.next
220 | if n == 1:
221 | stack[-n-1].next = None
222 | else:
223 | stack[-n-1].next = stack[-n+1]
224 | stack[-n].next = None
225 | return head
226 | ```
227 |
228 | 20 [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/)
229 | ```python
230 | class Solution(object):
231 | def isValid(self, s):
232 | """
233 | :type s: str
234 | :rtype: bool
235 | """
236 | left = ['(', '[', '{']
237 | stack = []
238 | for c in s:
239 | if c in left:
240 | stack.append(c)
241 | elif c == ')':
242 | if stack and stack[-1] == '(':
243 | stack.pop()
244 | else:
245 | return False
246 | elif c == ']':
247 | if stack and stack[-1] == '[':
248 | stack.pop()
249 | else:
250 | return False
251 | else:
252 | if stack and stack[-1] == '{':
253 | stack.pop()
254 | else:
255 | return False
256 | return len(stack) == 0
257 | ```
258 |
259 | 21 [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/description/)
260 | ```python
261 | class Solution(object):
262 | def mergeTwoLists(self, l1, l2):
263 | """
264 | :type l1: ListNode
265 | :type l2: ListNode
266 | :rtype: ListNode
267 | """
268 | pre = ret = ListNode(0)
269 | while l1 and l2:
270 | if l1.val <= l2.val:
271 | pre.next = l1
272 | l1 = l1.next
273 | else:
274 | pre.next = l2
275 | l2 = l2.next
276 | pre = pre.next
277 | while l1:
278 | pre.next = l1
279 | l1 = l1.next
280 | pre = pre.next
281 | while l2:
282 | pre.next = l2
283 | l2, pre = l2.next, pre.next
284 | return ret.next
285 | ```
286 |
287 | 23 [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/description/)
288 | ```python
289 | class Solution(object):
290 | def mergeKLists(self, lists):
291 | """
292 | :type lists: List[ListNode]
293 | :rtype: ListNode
294 | """
295 | import heapq
296 | min_heap = []
297 | ret = head = ListNode(0)
298 | for k, link in enumerate(lists):
299 | if link:
300 | heapq.heappush(min_heap, [link.val, link])
301 | while min_heap:
302 | cur = heapq.heappop(min_heap)
303 | ret.next = cur[-1]
304 | ret = ret.next
305 | if ret.next:
306 | heapq.heappush(min_heap, [ret.next.val, ret.next])
307 | return head.next
308 | ```
309 |
310 | 24 [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/description/)
311 | ```python
312 | class Solution(object):
313 | def swapPairs(self, head):
314 | """
315 | :type head: ListNode
316 | :rtype: ListNode
317 | """
318 | pre = m_pre = ListNode(0)
319 | pre.next = head
320 | while head and head.next:
321 | hn = head.next
322 | hnn = hn.next
323 | pre.next, hn.next, head.next = hn, head, hnn
324 | pre, head = head, hnn
325 | return m_pre.next
326 | ```
327 |
328 | 25 [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)
329 | ```python
330 | class Solution(object):
331 | def reverseKGroup(self, head, k):
332 | """
333 | :type head: ListNode
334 | :type k: int
335 | :rtype: ListNode
336 | """
337 | move, count = head, 0
338 | while move:
339 | count += 1
340 | move = move.next
341 | if count < k:
342 | return head
343 | move, current_count, current_last = head, 0, head
344 | move_pre = None
345 | while current_count < k:
346 | m_next = move.next
347 | move.next, move_pre = move_pre, move
348 | move = m_next
349 | current_count += 1
350 | current_last.next = self.reverseKGroup(move, k)
351 | return move_pre
352 | ```
353 |
354 | 26 [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/)
355 | ```python
356 | class Solution(object):
357 | def removeDuplicates(self, nums):
358 | """
359 | :type nums: List[int]
360 | :rtype: int
361 | """
362 | left = ret = 0
363 | cur = None
364 | while left < len(nums):
365 | if nums[left] != cur:
366 | nums[ret] = nums[left]
367 | ret += 1
368 | cur = nums[left]
369 | left += 1
370 | return ret
371 | ```
372 |
373 | 27 [Remove Element](https://leetcode.com/problems/remove-element/description/)
374 | ```python
375 | class Solution(object):
376 | def removeElement(self, nums, val):
377 | """
378 | :type nums: List[int]
379 | :type val: int
380 | :rtype: int
381 | """
382 | left, right = 0, len(nums) - 1
383 | while left <= right:
384 | if nums[left] == val:
385 | nums[left], nums[right] = nums[right], nums[left]
386 | right -= 1
387 | else:
388 | left += 1
389 | return left
390 | ```
391 |
392 | 28 [Implement strStr()](https://leetcode.com/problems/implement-strstr/description/)
393 | ```python
394 | class Solution(object):
395 | def strStr(self, haystack, needle):
396 | """
397 | :type haystack: str
398 | :type needle: str
399 | :rtype: int
400 | """
401 | return haystack.find(needle)
402 | ```
403 |
404 | 33 [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/description/)
405 | ```python
406 | class Solution(object):
407 |
408 | def find_min(self, nums):
409 | if not nums:
410 | return -1
411 | left, right = 0, len(nums) - 1
412 | while nums[left] > nums[right]:
413 | if right - left == 1:
414 | return right
415 | mid = (left + right) / 2
416 | if nums[left] <= nums[mid]:
417 | left = mid
418 | if nums[right] >= nums[mid]:
419 | right = mid
420 | return 0
421 |
422 | def search(self, nums, target):
423 | """
424 | :type nums: List[int]
425 | :type target: int
426 | :rtype: int
427 | """
428 | if not nums:
429 | return -1
430 | min_index = self.find_min(nums)
431 | if nums[min_index] == target:
432 | return min_index
433 | elif nums[min_index] > target:
434 | return -1
435 | else:
436 | left = self.search_t(nums, 0, min_index, target)
437 | right = self.search_t(nums, min_index, len(nums)-1, target)
438 | if left >= 0:
439 | return left
440 | if right >= 0:
441 | return right
442 | return -1
443 |
444 | def search_t(self, nums, left, right, target):
445 | while left <= right:
446 | mid = (left + right) / 2
447 | if nums[mid] == target:
448 | return mid
449 | elif nums[mid] < target:
450 | left = mid + 1
451 | else:
452 | right = mid - 1
453 | return -1
454 | ```
455 |
456 | 34 [Search for a Range](https://leetcode.com/problems/search-for-a-range/description/)
457 | ```python
458 | class Solution(object):
459 | def searchRange(self, nums, target):
460 | """
461 | :type nums: List[int]
462 | :type target: int
463 | :rtype: List[int]
464 | """
465 | return [self.search_left(nums, target), self.search_right(nums, target)]
466 |
467 | def search_left(self, nums, target):
468 | left, right = 0, len(nums) - 1
469 | while left <= right:
470 | mid = (left + right) / 2
471 | if nums[mid] == target:
472 | if mid == 0 or nums[mid-1] < target:
473 | return mid
474 | right = mid - 1
475 | elif nums[mid] < target:
476 | left = mid + 1
477 | else:
478 | right = mid - 1
479 | return -1
480 |
481 | def search_right(self, nums, target):
482 | left, right = 0, len(nums) - 1
483 | while left <= right:
484 | mid = (left + right) / 2
485 | if nums[mid] == target:
486 | if mid == len(nums) - 1 or nums[mid+1] > target:
487 | return mid
488 | left = mid + 1
489 | elif nums[mid] < target:
490 | left = mid + 1
491 | else:
492 | right = mid - 1
493 | return -1
494 | ```
495 |
496 | 35 [Search Insert Position](https://leetcode.com/problems/search-insert-position/description/)
497 | ```python
498 | class Solution(object):
499 | def searchInsert(self, nums, target):
500 | """
501 | :type nums: List[int]
502 | :type target: int
503 | :rtype: int
504 | """
505 | left, right = 0, len(nums) - 1
506 | mid = (left + right) / 2
507 | while left <= right:
508 | if nums[mid] == target:
509 | return mid
510 | elif nums[mid] > target:
511 | right = mid - 1
512 | else:
513 | left = mid + 1
514 | mid = (left + right) / 2
515 | if nums[mid] > target:
516 | return mid - 1 if mid > 0 else 0
517 | return mid + 1
518 | ```
519 |
520 | 38 [Count and Say](https://leetcode.com/problems/count-and-say/description/)
521 | ```python
522 | class Solution(object):
523 | def countAndSay(self, n):
524 | """
525 | :type n: int
526 | :rtype: str
527 | """
528 | start = '1'
529 | for i in range(n-1):
530 | c = start[0]
531 | nums = 0
532 | tmp = []
533 | for s in start:
534 | if s == c:
535 | nums += 1
536 | else:
537 | tmp.append([nums, c])
538 | nums = 1
539 | c = s
540 | tmp.append([nums, c])
541 | start = ''.join([str(d[0])+d[1] for d in tmp])
542 | return start
543 | ```
544 |
545 | 46 [Permutations](https://leetcode.com/problems/permutations/description/)
546 | ```Python
547 | class Solution(object):
548 | def permute(self, nums):
549 | """
550 | :type nums: List[int]
551 | :rtype: List[List[int]]
552 | """
553 | from itertools import permutations
554 | return list(permutations(nums))
555 | ```
556 |
557 | 47 [Permutations II](https://leetcode.com/problems/permutations-ii/description/)
558 | ```Python
559 | class Solution(object):
560 | def permuteUnique(self, nums):
561 | """
562 | :type nums: List[int]
563 | :rtype: List[List[int]]
564 | """
565 | from itertools import permutations
566 | return list(set(permutations(nums)))
567 | ```
568 |
569 | 48 [Rotate Image](https://leetcode.com/problems/rotate-image/description/)
570 | ```Python
571 | class Solution(object):
572 | def rotate(self, matrix):
573 | """
574 | :type matrix: List[List[int]]
575 | :rtype: void Do not return anything, modify matrix in-place instead.
576 | """
577 | n = len(matrix)
578 | m = 0
579 | while m <= n / 2:
580 | k = m
581 | while k < n - 1 - m:
582 | matrix[m][k], matrix[k][n-1-m], matrix[n-1-m][n-1-k], matrix[n-1-k][m] = \
583 | matrix[n-1-k][m], matrix[m][k], matrix[k][n-1-m], matrix[n-1-m][n-1-k]
584 | k += 1
585 | m += 1
586 | ```
587 |
588 | 49 [Group Anagrams](https://leetcode.com/problems/group-anagrams/description/)
589 | ```python
590 | class Solution(object):
591 | def groupAnagrams(self, strs):
592 | """
593 | :type strs: List[str]
594 | :rtype: List[List[str]]
595 | """
596 | ret = {}
597 | for s in strs:
598 | ts = ''.join(sorted(s))
599 | if ret.get(ts):
600 | ret[ts].append(s)
601 | else:
602 | ret[ts] = [s]
603 | return ret.values()
604 | ```
605 |
606 | 50 [Pow(x, n)](https://leetcode.com/problems/powx-n/description/)
607 | ```python
608 | class Solution(object):
609 | def myPow(self, x, n):
610 | """
611 | :type x: float
612 | :type n: int
613 | :rtype: float
614 | """
615 | return x ** n
616 | ```
617 |
618 |
--------------------------------------------------------------------------------
/500/451.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def frequencySort(self, s):
3 | """
4 | :type s: str
5 | :rtype: str
6 | """
7 | from collections import Counter
8 | c = Counter(s)
9 | return ''.join([i[0]*i[1] for i in c.most_common()])
10 |
--------------------------------------------------------------------------------
/500/454.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def fourSumCount(self, A, B, C, D):
3 | """
4 | :type A: List[int]
5 | :type B: List[int]
6 | :type C: List[int]
7 | :type D: List[int]
8 | :rtype: int
9 | """
10 | AB = {}
11 | for a in A:
12 | for b in B:
13 | AB[a+b] = AB.get(a+b, 0) + 1
14 | ret = 0
15 | for c in C:
16 | for d in D:
17 | if -c-d in AB:
18 | ret += AB.get(-c-d)
19 | return ret
20 |
--------------------------------------------------------------------------------
/500/455.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def findContentChildren(self, g, s):
3 | """
4 | :type g: List[int]
5 | :type s: List[int]
6 | :rtype: int
7 | """
8 | g.sort()
9 | s.sort()
10 | i, j = 0, 0
11 | while i < len(g) and j < len(s):
12 | if s[j] >= g[i]:
13 | i += 1
14 | j += 1
15 | return i
16 |
--------------------------------------------------------------------------------
/500/461.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def hammingDistance(self, x, y):
3 | """
4 | :type x: int
5 | :type y: int
6 | :rtype: int
7 | """
8 | return bin(x^y).count('1')
9 |
--------------------------------------------------------------------------------
/500/468.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def validIPAddress(self, IP):
3 | """
4 | :type IP: str
5 | :rtype: str
6 | """
7 | def is_ipv4(ip):
8 | sub = ip.split('.')
9 | for s in sub:
10 | if not s.isdigit() or (len(s) != len(str(int(s)))) or not (0 <= int(s) <= 255) :
11 | return False
12 | return len(sub) == 4
13 |
14 | def is_ipv6(ip):
15 | sub = ip.split(':')
16 | for s in sub:
17 | if len(s) > 4 or not ('0' <= s.upper() <= 'FFFF'):
18 | return False
19 | return len(sub) == 8
20 |
21 | if is_ipv4(IP):
22 | return 'IPv4'
23 | if is_ipv6(IP):
24 | return 'IPv6'
25 | return 'Neither'
26 |
--------------------------------------------------------------------------------
/500/476.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def findComplement(self, num):
3 | """
4 | :type num: int
5 | :rtype: int
6 | """
7 | return int(''.join(map(lambda x:'1' if x=='0' else '0', bin(num)[2:])), 2)
8 |
--------------------------------------------------------------------------------
/500/482.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def licenseKeyFormatting(self, S, K):
3 | """
4 | :type S: str
5 | :type K: int
6 | :rtype: str
7 | """
8 | s = S[::-1]
9 | ret = []
10 | leng = 0
11 | tmp = []
12 | for c in s:
13 | if c != '-':
14 | if leng == K:
15 | ret.append(''.join(tmp))
16 | leng = 1
17 | tmp = [c.upper()]
18 | else:
19 | tmp.append(c.upper())
20 | leng += 1
21 | ret.append(''.join(tmp))
22 | return '-'.join(ret)[::-1]
23 |
--------------------------------------------------------------------------------
/500/485.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def findMaxConsecutiveOnes(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: int
6 | """
7 | ret = tmp = 0
8 | for n in nums:
9 | if n:
10 | tmp += 1
11 | else:
12 | ret = max(tmp, ret)
13 | tmp = 0
14 | return max(ret, tmp)
15 |
--------------------------------------------------------------------------------
/500/492.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def constructRectangle(self, area):
3 | """
4 | :type area: int
5 | :rtype: List[int]
6 | """
7 | from math import sqrt
8 | s = int(sqrt(area))
9 | while area % s != 0:
10 | s -= 1
11 | return [area/ s, s]
12 |
--------------------------------------------------------------------------------
/500/500.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def findWords(self, words):
3 | """
4 | :type words: List[str]
5 | :rtype: List[str]
6 | """
7 | rows = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']
8 | # ret = []
9 | # for word in words:
10 | # if any([set(word.lower()).issubset(rows[0]),
11 | # set(word.lower()).issubset(rows[1]),
12 | # set(word.lower()).issubset(rows[2])]):
13 | # ret.append(word)
14 | # return ret
15 | return [word for word in words if any([set(word.lower()).issubset(row) for row in rows])]
16 |
--------------------------------------------------------------------------------
/500/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 451-500
2 |
3 | 451 [Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/description/)
4 | ```python
5 | class Solution(object):
6 | def frequencySort(self, s):
7 | """
8 | :type s: str
9 | :rtype: str
10 | """
11 | from collections import Counter
12 | c = Counter(s)
13 | return ''.join([i[0]*i[1] for i in c.most_common()])
14 | ```
15 |
16 | 454 [4Sum II](https://leetcode.com/problems/4sum-ii/description/)
17 | ```python
18 | class Solution(object):
19 | def fourSumCount(self, A, B, C, D):
20 | """
21 | :type A: List[int]
22 | :type B: List[int]
23 | :type C: List[int]
24 | :type D: List[int]
25 | :rtype: int
26 | """
27 | AB = {}
28 | for a in A:
29 | for b in B:
30 | AB[a+b] = AB.get(a+b, 0) + 1
31 | ret = 0
32 | for c in C:
33 | for d in D:
34 | if -c-d in AB:
35 | ret += AB.get(-c-d)
36 | return ret
37 | ```
38 |
39 | 455 [Assign Cookies](https://leetcode.com/problems/assign-cookies/description/)
40 | ```python
41 | class Solution(object):
42 | def findContentChildren(self, g, s):
43 | """
44 | :type g: List[int]
45 | :type s: List[int]
46 | :rtype: int
47 | """
48 | g.sort()
49 | s.sort()
50 | i, j = 0, 0
51 | while i < len(g) and j < len(s):
52 | if s[j] >= g[i]:
53 | i += 1
54 | j += 1
55 | return i
56 | ```
57 |
58 | 461 [Hamming Distance](https://leetcode.com/problems/hamming-distance/description/)
59 | ```python
60 | class Solution(object):
61 | def hammingDistance(self, x, y):
62 | """
63 | :type x: int
64 | :type y: int
65 | :rtype: int
66 | """
67 | return bin(x^y).count('1')
68 | ```
69 |
70 | 468 [Validate IP Address](https://leetcode.com/problems/validate-ip-address/description/)
71 | ```python
72 | class Solution(object):
73 | def validIPAddress(self, IP):
74 | """
75 | :type IP: str
76 | :rtype: str
77 | """
78 | def is_ipv4(ip):
79 | sub = ip.split('.')
80 | for s in sub:
81 | if not s.isdigit() or (len(s) != len(str(int(s)))) or not (0 <= int(s) <= 255) :
82 | return False
83 | return len(sub) == 4
84 |
85 | def is_ipv6(ip):
86 | sub = ip.split(':')
87 | for s in sub:
88 | if len(s) > 4 or not ('0' <= s.upper() <= 'FFFF'):
89 | return False
90 | return len(sub) == 8
91 |
92 | if is_ipv4(IP):
93 | return 'IPv4'
94 | if is_ipv6(IP):
95 | return 'IPv6'
96 | return 'Neither'
97 | ```
98 |
99 | 476 [Number Complement](https://leetcode.com/problems/number-complement/description/)
100 | ```python
101 | class Solution(object):
102 | def findComplement(self, num):
103 | """
104 | :type num: int
105 | :rtype: int
106 | """
107 | return int(''.join(map(lambda x:'1' if x=='0' else '0', bin(num)[2:])), 2)
108 | ```
109 |
110 | 482 [License Key Formatting](https://leetcode.com/problems/license-key-formatting/description/)
111 | ```python
112 | class Solution(object):
113 | def licenseKeyFormatting(self, S, K):
114 | """
115 | :type S: str
116 | :type K: int
117 | :rtype: str
118 | """
119 | s = S[::-1]
120 | ret = []
121 | leng = 0
122 | tmp = []
123 | for c in s:
124 | if c != '-':
125 | if leng == K:
126 | ret.append(''.join(tmp))
127 | leng = 1
128 | tmp = [c.upper()]
129 | else:
130 | tmp.append(c.upper())
131 | leng += 1
132 | ret.append(''.join(tmp))
133 | return '-'.join(ret)[::-1]
134 | ```
135 |
136 | 485 [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/description/)
137 | ```python
138 | class Solution(object):
139 | def findMaxConsecutiveOnes(self, nums):
140 | """
141 | :type nums: List[int]
142 | :rtype: int
143 | """
144 | ret = tmp = 0
145 | for n in nums:
146 | if n:
147 | tmp += 1
148 | else:
149 | ret = max(tmp, ret)
150 | tmp = 0
151 | return max(ret, tmp)
152 | ```
153 |
154 | 492 [Construct the Rectangle](https://leetcode.com/problems/construct-the-rectangle/description/)
155 | ```python
156 | class Solution(object):
157 | def constructRectangle(self, area):
158 | """
159 | :type area: int
160 | :rtype: List[int]
161 | """
162 | from math import sqrt
163 | s = int(sqrt(area))
164 | while area % s != 0:
165 | s -= 1
166 | return [area/ s, s]
167 | ```
168 |
169 | 500 [Keyboard Row](https://leetcode.com/problems/keyboard-row/description/)
170 | ```python
171 | class Solution(object):
172 | def findWords(self, words):
173 | """
174 | :type words: List[str]
175 | :rtype: List[str]
176 | """
177 | rows = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']
178 | return [word for word in words if any([set(word.lower()).issubset(row) for row in rows])]
179 | ```
180 |
181 |
182 |
183 |
--------------------------------------------------------------------------------
/550/504.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def convertToBase7(self, num):
3 | """
4 | :type num: int
5 | :rtype: str
6 | """
7 | if num == 0:
8 | return '0'
9 | ret = ''
10 | n = abs(num)
11 | while n:
12 | ret += str(n % 7)
13 | n = n / 7
14 | return '-' + ret[::-1] if num < 0 else ret[::-1]
15 |
--------------------------------------------------------------------------------
/550/507.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def checkPerfectNumber(self, num):
3 | """
4 | :type num: int
5 | :rtype: bool
6 | """
7 | from math import sqrt
8 | if num <= 3:
9 | return False
10 | tsum, end = 1, int(sqrt(num)) + 1
11 | for n in range(2, end):
12 | if num % n == 0:
13 | tsum += n + int(num / n)
14 | if tsum > num:
15 | return False
16 | return tsum == num
17 |
--------------------------------------------------------------------------------
/550/513.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def findBottomLeftValue(self, root):
10 | """
11 | :type root: TreeNode
12 | :rtype: int
13 | """
14 | from collections import deque
15 | d = deque()
16 | d.append(root)
17 | ret = root.val
18 | while d:
19 | node = d.popleft()
20 | ret = node.val
21 | if node.right:
22 | d.append(node.right)
23 | if node.left:
24 | d.append(node.left)
25 | return ret
26 |
--------------------------------------------------------------------------------
/550/515.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def largestValues(self, root):
10 | """
11 | :type root: TreeNode
12 | :rtype: List[int]
13 | """
14 | ret = []
15 | if not root:
16 | return ret
17 | level = 0
18 | node = [[root, level]]
19 | while node:
20 | ret.append(max(map(lambda x:x[0].val, node)))
21 | level += 1
22 | while node and node[0][1] < level:
23 | tmp = node.pop(0)
24 | if tmp[0].left:
25 | node.append([tmp[0].left, level])
26 | if tmp[0].right:
27 | node.append([tmp[0].right, level])
28 | return ret
29 |
--------------------------------------------------------------------------------
/550/520.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def detectCapitalUse(self, word):
3 | """
4 | :type word: str
5 | :rtype: bool
6 | """
7 | return word.islower() or word.isupper() or word.istitle()
8 |
--------------------------------------------------------------------------------
/550/530.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def getMinimumDifference(self, root):
10 | """
11 | :type root: TreeNode
12 | :rtype: int
13 | """
14 | ret = []
15 | def dfs(r):
16 | if r.left: dfs(r.left)
17 | ret.append(r.val)
18 | if r.right: dfs(r.right)
19 | dfs(root)
20 | return min([abs(ret[i]-ret[i+1]) for i in range(len(ret)-1)])
21 |
--------------------------------------------------------------------------------
/550/537.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def complexNumberMultiply(self, a, b):
3 | """
4 | :type a: str
5 | :type b: str
6 | :rtype: str
7 | """
8 | a, b = a.split('+'), b.split('+')
9 | a1, a2 = int(a[0]), int(a[1][:-1])
10 | b1, b2 = int(b[0]), int(b[1][:-1])
11 | c = a1 * b1 - a2 * b2
12 | d = a1 * b2 + a2 * b1
13 | return str(c) + '+' + str(d) +'i'
14 |
--------------------------------------------------------------------------------
/550/539.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def findMinDifference(self, timePoints):
3 | """
4 | :type timePoints: List[str]
5 | :rtype: int
6 | """
7 | t = sorted(int(t[:2]) * 60 + int(t[-2:]) for t in timePoints)
8 | ret = 100000
9 | length = len(t)
10 | for i in range(length - 1):
11 | poor = t[i+1] - t[i]
12 | if poor < ret:
13 | ret = poor
14 | last = t[-1] - t[0] if t[-1]-t[0] <= 720 else 1440 - (t[-1]-t[0])
15 | ret = last if last < ret else ret
16 | return ret
17 |
--------------------------------------------------------------------------------
/550/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 501-550
2 |
3 | 504 [Base 7](https://leetcode.com/problems/base-7/description/)
4 | ```python
5 | class Solution(object):
6 | def convertToBase7(self, num):
7 | """
8 | :type num: int
9 | :rtype: str
10 | """
11 | if num == 0:
12 | return '0'
13 | ret = ''
14 | n = abs(num)
15 | while n:
16 | ret += str(n % 7)
17 | n = n / 7
18 | return '-' + ret[::-1] if num < 0 else ret[::-1]
19 | ```
20 |
21 | 507 [Perfect Number](https://leetcode.com/problems/perfect-number/description/)
22 | ```python
23 | class Solution(object):
24 | def checkPerfectNumber(self, num):
25 | """
26 | :type num: int
27 | :rtype: bool
28 | """
29 | from math import sqrt
30 | if num <= 3:
31 | return False
32 | tsum, end = 1, int(sqrt(num)) + 1
33 | for n in range(2, end):
34 | if num % n == 0:
35 | tsum += n + int(num / n)
36 | if tsum > num:
37 | return False
38 | return tsum == num
39 | ```
40 |
41 | 513 [Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/description/)
42 | ```python
43 | class Solution(object):
44 | def findBottomLeftValue(self, root):
45 | """
46 | :type root: TreeNode
47 | :rtype: int
48 | """
49 | from collections import deque
50 | d = deque()
51 | d.append(root)
52 | ret = root.val
53 | while d:
54 | node = d.popleft()
55 | ret = node.val
56 | if node.right:
57 | d.append(node.right)
58 | if node.left:
59 | d.append(node.left)
60 | return ret
61 | ```
62 |
63 | 515 [Find Largest Value in Each Tree Row](https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/)
64 | ```python
65 | class Solution(object):
66 | def largestValues(self, root):
67 | """
68 | :type root: TreeNode
69 | :rtype: List[int]
70 | """
71 | ret = []
72 | if not root:
73 | return ret
74 | level = 0
75 | node = [[root, level]]
76 | while node:
77 | ret.append(max(map(lambda x:x[0].val, node)))
78 | level += 1
79 | while node and node[0][1] < level:
80 | tmp = node.pop(0)
81 | if tmp[0].left:
82 | node.append([tmp[0].left, level])
83 | if tmp[0].right:
84 | node.append([tmp[0].right, level])
85 | return ret
86 | ```
87 |
88 | 520 [Detect Capital](https://leetcode.com/problems/detect-capital/description/)
89 | ```python
90 | class Solution(object):
91 | def detectCapitalUse(self, word):
92 | """
93 | :type word: str
94 | :rtype: bool
95 | """
96 | return word.islower() or word.isupper() or word.istitle()
97 | ```
98 |
99 | 530 [Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/)
100 | ```python
101 | class Solution(object):
102 | def getMinimumDifference(self, root):
103 | """
104 | :type root: TreeNode
105 | :rtype: int
106 | """
107 | ret = []
108 | def dfs(r):
109 | if r.left: dfs(r.left)
110 | ret.append(r.val)
111 | if r.right: dfs(r.right)
112 | dfs(root)
113 | return min([abs(ret[i]-ret[i+1]) for i in range(len(ret)-1)])
114 | ```
115 |
116 | 537 [Complex Number Multiplication](https://leetcode.com/problems/complex-number-multiplication/description/)
117 | ```python
118 | class Solution(object):
119 | def complexNumberMultiply(self, a, b):
120 | """
121 | :type a: str
122 | :type b: str
123 | :rtype: str
124 | """
125 | a, b = a.split('+'), b.split('+')
126 | a1, a2 = int(a[0]), int(a[1][:-1])
127 | b1, b2 = int(b[0]), int(b[1][:-1])
128 | c = a1 * b1 - a2 * b2
129 | d = a1 * b2 + a2 * b1
130 | return str(c) + '+' + str(d) +'i'
131 | ```
132 |
133 | 539 [Minimum Time Difference](https://leetcode.com/problems/minimum-time-difference/description/)
134 | ```Python
135 | class Solution(object):
136 | def findMinDifference(self, timePoints):
137 | """
138 | :type timePoints: List[str]
139 | :rtype: int
140 | """
141 | t = sorted(int(t[:2]) * 60 + int(t[-2:]) for t in timePoints)
142 | ret = 100000
143 | length = len(t)
144 | for i in range(length - 1):
145 | poor = t[i+1] - t[i]
146 | if poor < ret:
147 | ret = poor
148 | last = t[-1] - t[0] if t[-1]-t[0] <= 720 else 1440 - (t[-1]-t[0])
149 | ret = last if last < ret else ret
150 | return ret
151 | ```
152 |
--------------------------------------------------------------------------------
/600/551.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def checkRecord(self, s):
3 | """
4 | :type s: str
5 | :rtype: bool
6 | """
7 | return s.count('A') < 2 and 'LLL' not in s
8 |
--------------------------------------------------------------------------------
/600/557.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def reverseWords(self, s):
3 | """
4 | :type s: str
5 | :rtype: str
6 | """
7 | return ' '.join(map(lambda t:t[::-1], s.split(' ')))
8 |
--------------------------------------------------------------------------------
/600/572.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def isSubtree(self, s, t):
10 | """
11 | :type s: TreeNode
12 | :type t: TreeNode
13 | :rtype: bool
14 | """
15 | if not s:
16 | return False
17 | if self.isSame(s, t):
18 | return True
19 | return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
20 |
21 | def isSame(self, s, t):
22 | if not s and not t:
23 | return True
24 | if not s or not t:
25 | return False
26 | if s.val != t.val:
27 | return False
28 | return self.isSame(s.left, t.left) and self.isSame(s.right, t.right)
29 |
--------------------------------------------------------------------------------
/600/593.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def validSquare(self, p1, p2, p3, p4):
3 | """
4 | :type p1: List[int]
5 | :type p2: List[int]
6 | :type p3: List[int]
7 | :type p4: List[int]
8 | :rtype: bool
9 | """
10 | a = (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2
11 | b = (p1[0] - p3[0]) ** 2 + (p1[1] - p3[1]) ** 2
12 | c = (p1[0] - p4[0]) ** 2 + (p1[1] - p4[1]) ** 2
13 | d = (p2[0] - p3[0]) ** 2 + (p3[1] - p2[1]) ** 2
14 | e = (p4[0] - p2[0]) ** 2 + (p4[1] - p2[1]) ** 2
15 | f = (p3[0] - p4[0]) ** 2 + (p3[1] - p4[1]) ** 2
16 | counter = set([a, b, c, d, e, f])
17 | if len(counter) == 2:
18 | t = [a, b, c, d, e, f]
19 | m, s = counter
20 | u = t.count(m)
21 | v = t.count(s)
22 | return (u == 4 and 2 * m == s) or (v == 4 and 2 * s == m)
23 | return False
24 |
25 |
--------------------------------------------------------------------------------
/600/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 551-600
2 |
3 | 551 [Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i/description/)
4 | ```python
5 | class Solution(object):
6 | def checkRecord(self, s):
7 | """
8 | :type s: str
9 | :rtype: bool
10 | """
11 | return s.count('A') < 2 and 'LLL' not in s
12 | ```
13 |
14 | 557 [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/description/)
15 | ```python
16 | class Solution(object):
17 | def reverseWords(self, s):
18 | """
19 | :type s: str
20 | :rtype: str
21 | """
22 | return ' '.join(map(lambda t:t[::-1], s.split(' ')))
23 | ```
24 |
25 | 572 [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)
26 | ```python
27 | class Solution(object):
28 | def isSubtree(self, s, t):
29 | """
30 | :type s: TreeNode
31 | :type t: TreeNode
32 | :rtype: bool
33 | """
34 | if not s:
35 | return False
36 | if self.isSame(s, t):
37 | return True
38 | return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
39 |
40 | def isSame(self, s, t):
41 | if not s and not t:
42 | return True
43 | if not s or not t:
44 | return False
45 | if s.val != t.val:
46 | return False
47 | return self.isSame(s.left, t.left) and self.isSame(s.right, t.right)
48 | ```
49 |
50 | 593 [Valid Square](https://leetcode.com/problems/valid-square/description/)
51 | ```python
52 | class Solution(object):
53 | def validSquare(self, p1, p2, p3, p4):
54 | """
55 | :type p1: List[int]
56 | :type p2: List[int]
57 | :type p3: List[int]
58 | :type p4: List[int]
59 | :rtype: bool
60 | """
61 | a = (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2
62 | b = (p1[0] - p3[0]) ** 2 + (p1[1] - p3[1]) ** 2
63 | c = (p1[0] - p4[0]) ** 2 + (p1[1] - p4[1]) ** 2
64 | d = (p2[0] - p3[0]) ** 2 + (p3[1] - p2[1]) ** 2
65 | e = (p4[0] - p2[0]) ** 2 + (p4[1] - p2[1]) ** 2
66 | f = (p3[0] - p4[0]) ** 2 + (p3[1] - p4[1]) ** 2
67 | counter = set([a, b, c, d, e, f])
68 | if len(counter) == 2:
69 | t = [a, b, c, d, e, f]
70 | m, s = counter
71 | u = t.count(m)
72 | v = t.count(s)
73 | return (u == 4 and 2 * m == s) or (v == 4 and 2 * s == m)
74 | return False
75 | ```
76 |
--------------------------------------------------------------------------------
/650/606.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def tree2str(self, t):
10 | """
11 | :type t: TreeNode
12 | :rtype: str
13 | """
14 | if not t:
15 | return ''
16 | root = str(t.val)
17 | left = self.tree2str(t.left)
18 | right = self.tree2str(t.right)
19 | if right:
20 | return root + '(' + left + ')(' + right + ')'
21 | else:
22 | if left:
23 | return root + '(' + left + ')'
24 | else:
25 | return root
26 |
--------------------------------------------------------------------------------
/650/617.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def mergeTrees(self, t1, t2):
10 | """
11 | :type t1: TreeNode
12 | :type t2: TreeNode
13 | :rtype: TreeNode
14 | """
15 | if not t1:
16 | return t2
17 | if not t2:
18 | return t1
19 | root = TreeNode(t1.val+t2.val)
20 | root.left = self.mergeTrees(t1.left, t2.left)
21 | root.right = self.mergeTrees(t1.right, t2.right)
22 | return root
23 |
24 |
--------------------------------------------------------------------------------
/650/633.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def judgeSquareSum(self, c):
3 | """
4 | :type c: int
5 | :rtype: bool
6 | """
7 | from math import sqrt
8 | for i in range(int(sqrt(c))+1):
9 | if (int(sqrt(c-i**2))) ** 2 + i ** 2 == c:
10 | return True
11 | return False
12 |
--------------------------------------------------------------------------------
/650/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 601-650
2 |
3 | 606 [Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/description/)
4 | ```python
5 | class Solution(object):
6 | def tree2str(self, t):
7 | """
8 | :type t: TreeNode
9 | :rtype: str
10 | """
11 | if not t:
12 | return ''
13 | root = str(t.val)
14 | left = self.tree2str(t.left)
15 | right = self.tree2str(t.right)
16 | if right:
17 | return root + '(' + left + ')(' + right + ')'
18 | else:
19 | if left:
20 | return root + '(' + left + ')'
21 | else:
22 | return root
23 | ```
24 |
25 | 617 [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/description/)
26 | ```python
27 | class Solution(object):
28 | def mergeTrees(self, t1, t2):
29 | """
30 | :type t1: TreeNode
31 | :type t2: TreeNode
32 | :rtype: TreeNode
33 | """
34 | if not t1:
35 | return t2
36 | if not t2:
37 | return t1
38 | root = TreeNode(t1.val+t2.val)
39 | root.left = self.mergeTrees(t1.left, t2.left)
40 | root.right = self.mergeTrees(t1.right, t2.right)
41 | return root
42 | ```
43 |
44 | 633 [Sum of Square Numbers](https://leetcode.com/problems/sum-of-square-numbers/description/)
45 | ```python
46 | class Solution(object):
47 | def judgeSquareSum(self, c):
48 | """
49 | :type c: int
50 | :rtype: bool
51 | """
52 | from math import sqrt
53 | for i in range(int(sqrt(c))+1):
54 | if (int(sqrt(c-i**2))) ** 2 + i ** 2 == c:
55 | return True
56 | return False
57 | ```
58 |
--------------------------------------------------------------------------------
/700/654.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def constructMaximumBinaryTree(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: TreeNode
6 | """
7 | if not nums:
8 | return None
9 | max_value = max(nums)
10 | max_index = nums.index(max_value)
11 | root = TreeNode(max_value)
12 | root.left = self.constructMaximumBinaryTree(nums[:max_index])
13 | root.right = self.constructMaximumBinaryTree(nums[max_index+1:])
14 | return root
15 |
--------------------------------------------------------------------------------
/700/657.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def judgeCircle(self, moves):
3 | """
4 | :type moves: str
5 | :rtype: bool
6 | """
7 | row = col = 0
8 | for s in moves:
9 | if s == 'U':
10 | col += 1
11 | elif s == 'D':
12 | col -= 1
13 | elif s == 'L':
14 | row -= 1
15 | elif s == 'R':
16 | row += 1
17 | else:
18 | pass
19 | if row == 0 and col == 0:
20 | return True
21 | return False
22 |
23 |
--------------------------------------------------------------------------------
/700/671.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def findSecondMinimumValue(self, root):
10 | """
11 | :type root: TreeNode
12 | :rtype: int
13 | """
14 | from collections import deque
15 | if not root:
16 | return -1
17 | stack = deque([root])
18 | ret = [root.val]
19 | while stack:
20 | node = stack.popleft()
21 | if node:
22 | if node.val > ret[-1]:
23 | if len(ret) < 2:
24 | ret.append(node.val)
25 | else:
26 | if ret[0] < node.val < ret[1]:
27 | ret[1] = node.val
28 | stack.append(node.left)
29 | stack.append(node.right)
30 | return ret[1] if len(ret) == 2 else -1
31 |
--------------------------------------------------------------------------------
/700/674.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def findLengthOfLCIS(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: int
6 | """
7 | ret, tmp = 0, 0
8 | pre = float('-inf')
9 | for n in nums:
10 | if n > pre:
11 | tmp += 1
12 | else:
13 | ret = max(ret, tmp)
14 | tmp = 1
15 | pre = n
16 | return max(ret, tmp)
17 |
--------------------------------------------------------------------------------
/700/680.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 |
3 | def isPalindrome(self, s, left, right, flag):
4 | while left < right:
5 | if s[left] == s[right]:
6 | left += 1
7 | right -= 1
8 | else:
9 | if flag == 1:
10 | return False
11 | flag = 1
12 | return (self.isPalindrome(s, left+1, right, flag) or
13 | self.isPalindrome(s, left, right-1, flag))
14 | return True
15 |
16 | def validPalindrome(self, s):
17 | """
18 | :type s: str
19 | :rtype: bool
20 | """
21 | return self.isPalindrome(s, 0, len(s)-1, 0)
22 |
--------------------------------------------------------------------------------
/700/693.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def hasAlternatingBits(self, n):
3 | """
4 | :type n: int
5 | :rtype: bool
6 | """
7 | a = n % 2
8 | n = n >> 1
9 | while n:
10 | t = n % 2
11 | if t == a:
12 | return False
13 | a = t
14 | n = n >> 1
15 | return a != n
16 |
--------------------------------------------------------------------------------
/700/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 650-700
2 |
3 | 654 [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/description/)
4 | ```Python
5 | class Solution(object):
6 | def constructMaximumBinaryTree(self, nums):
7 | """
8 | :type nums: List[int]
9 | :rtype: TreeNode
10 | """
11 | if not nums:
12 | return None
13 | max_value = max(nums)
14 | max_index = nums.index(max_value)
15 | root = TreeNode(max_value)
16 | root.left = self.constructMaximumBinaryTree(nums[:max_index])
17 | root.right = self.constructMaximumBinaryTree(nums[max_index+1:])
18 | return root
19 | ```
20 |
21 | 657 [Judge Route Circle](https://leetcode.com/problems/judge-route-circle/description/)
22 | ```python
23 | class Solution(object):
24 | def judgeCircle(self, moves):
25 | """
26 | :type moves: str
27 | :rtype: bool
28 | """
29 | row = col = 0
30 | for s in moves:
31 | if s == 'U':
32 | col += 1
33 | elif s == 'D':
34 | col -= 1
35 | elif s == 'L':
36 | row -= 1
37 | elif s == 'R':
38 | row += 1
39 | else:
40 | pass
41 | if row == 0 and col == 0:
42 | return True
43 | return False
44 | ```
45 |
46 | 671 [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/description/)
47 | ```Python
48 | class Solution(object):
49 | def findSecondMinimumValue(self, root):
50 | """
51 | :type root: TreeNode
52 | :rtype: int
53 | """
54 | from collections import deque
55 | if not root:
56 | return -1
57 | stack = deque([root])
58 | ret = [root.val]
59 | while stack:
60 | node = stack.popleft()
61 | if node:
62 | if node.val > ret[-1]:
63 | if len(ret) < 2:
64 | ret.append(node.val)
65 | else:
66 | if ret[0] < node.val < ret[1]:
67 | ret[1] = node.val
68 | stack.append(node.left)
69 | stack.append(node.right)
70 | return ret[1] if len(ret) == 2 else -1
71 | ```
72 |
73 | 674 [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/)
74 | ```python
75 | class Solution(object):
76 | def findLengthOfLCIS(self, nums):
77 | """
78 | :type nums: List[int]
79 | :rtype: int
80 | """
81 | ret, tmp = 0, 0
82 | pre = float('-inf')
83 | for n in nums:
84 | if n > pre:
85 | tmp += 1
86 | else:
87 | ret = max(ret, tmp)
88 | tmp = 1
89 | pre = n
90 | return max(ret, tmp)
91 | ```
92 |
93 | 680 [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/description/)
94 | ```Python
95 | class Solution(object):
96 |
97 | def isPalindrome(self, s, left, right, flag):
98 | while left < right:
99 | if s[left] == s[right]:
100 | left += 1
101 | right -= 1
102 | else:
103 | if flag == 1:
104 | return False
105 | flag = 1
106 | return (self.isPalindrome(s, left+1, right, flag) or
107 | self.isPalindrome(s, left, right-1, flag))
108 | return True
109 |
110 | def validPalindrome(self, s):
111 | """
112 | :type s: str
113 | :rtype: bool
114 | """
115 | return self.isPalindrome(s, 0, len(s)-1, 0)
116 | ```
117 |
118 | 693 [Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits/description/)
119 | ```python
120 | class Solution(object):
121 | def hasAlternatingBits(self, n):
122 | """
123 | :type n: int
124 | :rtype: bool
125 | """
126 | a = n % 2
127 | n = n >> 1
128 | while n:
129 | t = n % 2
130 | if t == a:
131 | return False
132 | a = t
133 | n = n >> 1
134 | return a != n
135 | ```
136 |
137 |
138 |
--------------------------------------------------------------------------------
/750/709.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | class Solution(object):
3 | def toLowerCase(self, str):
4 | """
5 | :type str: str
6 | :rtype: str
7 | """
8 | return str.lower()
9 |
--------------------------------------------------------------------------------
/750/717.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def isOneBitCharacter(self, bits):
3 | """
4 | :type bits: List[int]
5 | :rtype: bool
6 | """
7 | length, mv = len(bits), 0
8 | while mv < length - 1:
9 | mv += (1 + bits[mv])
10 | return mv <= length - 1
--------------------------------------------------------------------------------
/750/724.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def pivotIndex(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: int
6 | """
7 | ret = sum(nums)
8 | left = 0
9 | for k, v in enumerate(nums):
10 | if left * 2 + v == ret:
11 | return k
12 | left += v
13 | return -1
14 |
15 |
--------------------------------------------------------------------------------
/750/725.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution(object):
8 | def splitListToParts(self, root, k):
9 | """
10 | :type root: ListNode
11 | :type k: int
12 | :rtype: List[ListNode]
13 | """
14 | ret = [None] * k
15 | length, move = 0, root
16 | while move:
17 | length += 1
18 | move = move.next
19 | avg, rem = length / k, length % k
20 | move, indexs = root, 0
21 | while move:
22 | tmp = move
23 | pre = ListNode(0)
24 | pre.next = move
25 | num = 0
26 | while num < avg:
27 | pre, move = pre.next, move.next
28 | num += 1
29 | if rem:
30 | pre, move = pre.next, move.next
31 | rem -= 1
32 | pre.next = None
33 | ret[indexs] = tmp
34 | indexs += 1
35 | return ret
36 |
--------------------------------------------------------------------------------
/750/728.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def selfDividingNumbers(self, left, right):
3 | """
4 | :type left: int
5 | :type right: int
6 | :rtype: List[int]
7 | """
8 | ret = []
9 | for i in range(left, right+1):
10 | val = i
11 | flag = 1
12 | while i:
13 | remain = i % 10
14 | if not remain or val % remain != 0:
15 | flag = 0
16 | break
17 | i /= 10
18 | if flag:
19 | ret.append(val)
20 | return ret
21 |
22 |
--------------------------------------------------------------------------------
/750/744.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def nextGreatestLetter(self, letters, target):
3 | """
4 | :type letters: List[str]
5 | :type target: str
6 | :rtype: str
7 | """
8 | left, right = 0, len(letters) - 1
9 | while left <= right:
10 | mid = (left + right) / 2
11 | if letters[mid] <= target:
12 | left = mid + 1
13 | else:
14 | if mid < 1 or (mid >= 1 and letters[mid-1] <= target):
15 | return letters[mid]
16 | right = mid - 1
17 | return letters[0]
18 |
--------------------------------------------------------------------------------
/750/747.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def dominantIndex(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: int
6 | """
7 | if len(nums) < 2:
8 | return 0
9 | a, b = [nums[0], 0], [nums[1], 1]
10 | if b[0] > a[0]:
11 | a, b = b, a
12 | for k, v in enumerate(nums):
13 | if k < 2:
14 | continue
15 | if b[0] < v < a[0]:
16 | b = [v, k]
17 | elif v >= a[0]:
18 | a, b = [v, k], a
19 | else:
20 | pass
21 | return a[1] if a[0] >= b[0] * 2 else -1
22 |
23 |
--------------------------------------------------------------------------------
/750/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 701-750
2 |
3 | [709. To Lower Case](https://leetcode.com/problems/to-lower-case/)
4 | ```python
5 | class Solution(object):
6 | def toLowerCase(self, str):
7 | """
8 | :type str: str
9 | :rtype: str
10 | """
11 | return str.lower()
12 | ```
13 |
14 | [717. 1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/)
15 | ```python
16 | class Solution(object):
17 | def isOneBitCharacter(self, bits):
18 | """
19 | :type bits: List[int]
20 | :rtype: bool
21 | """
22 | length, mv = len(bits), 0
23 | while mv < length - 1:
24 | mv += (1 + bits[mv])
25 | return mv <= length - 1
26 | ```
27 |
28 | [724. Find Pivot Index](https://leetcode.com/problems/find-pivot-index/description/)
29 | ```python
30 | class Solution(object):
31 | def pivotIndex(self, nums):
32 | """
33 | :type nums: List[int]
34 | :rtype: int
35 | """
36 | ret = sum(nums)
37 | left = 0
38 | for k, v in enumerate(nums):
39 | if left * 2 + v == ret:
40 | return k
41 | left += v
42 | return -1
43 | ```
44 |
45 | [725. Split Linked List in Parts](https://leetcode.com/problems/split-linked-list-in-parts/description/)
46 | ```Python
47 | class Solution(object):
48 | def splitListToParts(self, root, k):
49 | """
50 | :type root: ListNode
51 | :type k: int
52 | :rtype: List[ListNode]
53 | """
54 | ret = [None] * k
55 | length, move = 0, root
56 | while move:
57 | length += 1
58 | move = move.next
59 | avg, rem = length / k, length % k
60 | move, indexs = root, 0
61 | while move:
62 | tmp = move
63 | pre = ListNode(0)
64 | pre.next = move
65 | num = 0
66 | while num < avg:
67 | pre, move = pre.next, move.next
68 | num += 1
69 | if rem:
70 | pre, move = pre.next, move.next
71 | rem -= 1
72 | pre.next = None
73 | ret[indexs] = tmp
74 | indexs += 1
75 | return ret
76 | ```
77 |
78 | [728. Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/description/)
79 | ```Python
80 | class Solution(object):
81 | def selfDividingNumbers(self, left, right):
82 | """
83 | :type left: int
84 | :type right: int
85 | :rtype: List[int]
86 | """
87 | ret = []
88 | for i in range(left, right+1):
89 | val = i
90 | flag = 1
91 | while i:
92 | remain = i % 10
93 | if not remain or val % remain != 0:
94 | flag = 0
95 | break
96 | i /= 10
97 | if flag:
98 | ret.append(val)
99 | return ret
100 | ```
101 |
102 | 744 [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/)
103 | ```python
104 | class Solution(object):
105 | def nextGreatestLetter(self, letters, target):
106 | """
107 | :type letters: List[str]
108 | :type target: str
109 | :rtype: str
110 | """
111 | left, right = 0, len(letters) - 1
112 | while left <= right:
113 | mid = (left + right) / 2
114 | if letters[mid] <= target:
115 | left = mid + 1
116 | else:
117 | if mid < 1 or (mid >= 1 and letters[mid-1] <= target):
118 | return letters[mid]
119 | right = mid - 1
120 | return letters[0]
121 | ```
122 |
123 | 747 [Largest Number Greater Than Twice of Others](https://leetcode.com/problems/largest-number-greater-than-twice-of-others/description/)
124 | ```python
125 | class Solution(object):
126 | def dominantIndex(self, nums):
127 | """
128 | :type nums: List[int]
129 | :rtype: int
130 | """
131 | if len(nums) < 2:
132 | return 0
133 | a, b = [nums[0], 0], [nums[1], 1]
134 | if b[0] > a[0]:
135 | a, b = b, a
136 | for k, v in enumerate(nums):
137 | if k < 2:
138 | continue
139 | if b[0] < v < a[0]:
140 | b = [v, k]
141 | elif v >= a[0]:
142 | a, b = [v, k], a
143 | else:
144 | pass
145 | return a[1] if a[0] >= b[0] * 2 else -1
146 | ```
147 |
--------------------------------------------------------------------------------
/800/771.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def numJewelsInStones(self, J, S):
3 | """
4 | :type J: str
5 | :type S: str
6 | :rtype: int
7 | """
8 | j_hash = {c: True for c in J}
9 | ret = 0
10 | for c in S:
11 | if j_hash.get(c):
12 | ret += 1
13 | return ret
14 |
--------------------------------------------------------------------------------
/800/783.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode(object):
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution(object):
9 | def minDiffInBST(self, root):
10 | """
11 | :type root: TreeNode
12 | :rtype: int
13 | """
14 | ret = []
15 |
16 | def dfs(root):
17 | if not root:
18 | return
19 | dfs(root.left)
20 | ret.append(root.val)
21 | dfs(root.right)
22 |
23 | dfs(root)
24 | return min([ret[i] - ret[i - 1] for i in range(1, len(ret))])
25 |
--------------------------------------------------------------------------------
/800/791.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def customSortString(self, S, T):
3 | """
4 | :type S: str
5 | :type T: str
6 | :rtype: str
7 | """
8 | s_hash = {}
9 | t_hash = {}
10 | for c in T:
11 | t_hash[c] = t_hash.get(c, 0) + 1
12 | ret = []
13 | for c in S:
14 | if t_hash.get(c):
15 | ret.append(c * t_hash.get(c))
16 | del t_hash[c]
17 | for k in t_hash.keys():
18 | ret.append(k * t_hash[k])
19 | return ''.join(ret)
--------------------------------------------------------------------------------
/800/796.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def rotateString(self, A, B):
3 | """
4 | :type A: str
5 | :type B: str
6 | :rtype: bool
7 | """
8 | return len(A) == len(B) and B in (A + A)
9 |
--------------------------------------------------------------------------------
/800/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode 751-800
2 |
3 | 771 [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/)
4 | ```python
5 | class Solution(object):
6 | def numJewelsInStones(self, J, S):
7 | """
8 | :type J: str
9 | :type S: str
10 | :rtype: int
11 | """
12 | j_hash = {c: True for c in J}
13 | ret = 0
14 | for c in S:
15 | if j_hash.get(c):
16 | ret += 1
17 | return ret
18 | ```
19 |
20 | 783 [Minimum Distance Between BST Nodes](https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/)
21 | ```python
22 | class Solution(object):
23 | def minDiffInBST(self, root):
24 | """
25 | :type root: TreeNode
26 | :rtype: int
27 | """
28 | ret = []
29 | def dfs(root):
30 | if not root:
31 | return
32 | dfs(root.left)
33 | ret.append(root.val)
34 | dfs(root.right)
35 | dfs(root)
36 | return min([ret[i] - ret[i-1] for i in range(1, len(ret))])
37 | ```
38 |
39 | 791 [Custom Sort String](https://leetcode.com/problems/custom-sort-string/description/)
40 | ```python
41 | class Solution(object):
42 | def customSortString(self, S, T):
43 | """
44 | :type S: str
45 | :type T: str
46 | :rtype: str
47 | """
48 | s_hash = {}
49 | t_hash = {}
50 | for c in T:
51 | t_hash[c] = t_hash.get(c, 0) + 1
52 | ret = []
53 | for c in S:
54 | if t_hash.get(c):
55 | ret.append(c * t_hash.get(c))
56 | del t_hash[c]
57 | for k in t_hash.keys():
58 | ret.append(k * t_hash[k])
59 | return ''.join(ret)
60 | ```
61 | 796 [Rotate String](https://leetcode.com/problems/rotate-string/description/)
62 | ```python
63 | class Solution(object):
64 | def rotateString(self, A, B):
65 | """
66 | :type A: str
67 | :type B: str
68 | :rtype: bool
69 | """
70 | return len(A) == len(B) and B in (A + A)
71 | ```
72 |
--------------------------------------------------------------------------------
/950/905.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def sortArrayByParity(self, A):
3 | """
4 | :type A: List[int]
5 | :rtype: List[int]
6 | """
7 | start, end = 0, len(A) - 1
8 | while start <= end:
9 | if A[start] % 2 and not A[end] % 2:
10 | A[start], A[end] = A[end], A[start]
11 | start += 1
12 | end -= 1
13 | elif A[start] % 2 and A[end] % 2:
14 | end -= 1
15 | elif not A[start] % 2 and not A[end] % 2:
16 | start += 1
17 | else:
18 | start += 1
19 | end -= 1
20 | return A
21 |
--------------------------------------------------------------------------------
/950/908.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def smallestRangeI(self, A, K):
3 | """
4 | :type A: List[int]
5 | :type K: int
6 | :rtype: int
7 | """
8 | mi = ma = -1
9 | for a in A:
10 | mi = min(mi, a) if mi > -1 else a
11 | ma = max(ma, a) if ma > -1 else a
12 | return 0 if 2 * K > ma - mi else ma - mi - 2 * K
--------------------------------------------------------------------------------
/950/917.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def reverseOnlyLetters(self, S):
3 | """
4 | :type S: str
5 | :rtype: str
6 | """
7 | s = list(S)
8 | l, r = 0, len(s) - 1
9 | while l < r:
10 | if s[l].isalpha() and s[r].isalpha():
11 | s[l], s[r] = s[r], s[l]
12 | l += 1
13 | r -= 1
14 | elif s[l].isalpha() and not s[r].isalpha():
15 | r -= 1
16 | elif not s[l].isalpha() and s[r].isalpha():
17 | l += 1
18 | else:
19 | l += 1
20 | r -= 1
21 | return ''.join(s)
--------------------------------------------------------------------------------
/950/922.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def sortArrayByParityII(self, A):
3 | """
4 | :type A: List[int]
5 | :rtype: List[int]
6 | """
7 | even, odd, length = 0, 1, len(A)
8 | while odd < length and even < length:
9 | if A[even] % 2 != 0 and A[odd] % 2 == 0:
10 | A[even], A[odd] = A[odd], A[even]
11 | odd += 2
12 | even += 2
13 | elif A[even] % 2 != 0 and A[odd] % 2 != 0:
14 | odd += 2
15 | elif A[even] % 2 == 0 and A[odd] % 2 == 0:
16 | even += 2
17 | else:
18 | odd += 2
19 | even += 2
20 | return A
--------------------------------------------------------------------------------
/950/929.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def numUniqueEmails(self, emails):
3 | """
4 | :type emails: List[str]
5 | :rtype: int
6 | """
7 | return len({self.simplifyEmail(email): True for email in emails})
8 |
9 | def simplifyEmail(self, email):
10 | name, domain = email.split('@')
11 | return ''.join(name.split('+')[0].split('.')) + '@' + domain
12 |
--------------------------------------------------------------------------------
/950/README.md:
--------------------------------------------------------------------------------
1 | # LeegtCode 901-950
2 |
3 | 905 [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/)
4 | ```python
5 | class Solution(object):
6 | def sortArrayByParity(self, A):
7 | """
8 | :type A: List[int]
9 | :rtype: List[int]
10 | """
11 | start, end = 0, len(A) - 1
12 | while start <= end:
13 | if A[start] % 2 and not A[end] % 2:
14 | A[start], A[end] = A[end], A[start]
15 | start += 1
16 | end -= 1
17 | elif A[start] % 2 and A[end] % 2:
18 | end -= 1
19 | elif not A[start] % 2 and not A[end] % 2:
20 | start += 1
21 | else:
22 | start += 1
23 | end -= 1
24 | return A
25 | ```
26 |
27 | 908 [Smallest Range I](https://leetcode.com/problems/smallest-range-i/)
28 | ```python
29 | class Solution(object):
30 | def smallestRangeI(self, A, K):
31 | """
32 | :type A: List[int]
33 | :type K: int
34 | :rtype: int
35 | """
36 | mi = ma = -1
37 | for a in A:
38 | mi = min(mi, a) if mi > -1 else a
39 | ma = max(ma, a) if ma > -1 else a
40 | return 0 if 2 * K > ma - mi else ma - mi - 2 * K
41 | ```
42 |
43 | 917 [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters/)
44 | ```python
45 | class Solution(object):
46 | def reverseOnlyLetters(self, S):
47 | """
48 | :type S: str
49 | :rtype: str
50 | """
51 | s = list(S)
52 | l, r = 0, len(s) - 1
53 | while l < r:
54 | if s[l].isalpha() and s[r].isalpha():
55 | s[l], s[r] = s[r], s[l]
56 | l += 1
57 | r -= 1
58 | elif s[l].isalpha() and not s[r].isalpha():
59 | r -= 1
60 | elif not s[l].isalpha() and s[r].isalpha():
61 | l += 1
62 | else:
63 | l += 1
64 | r -= 1
65 | return ''.join(s)
66 | ```
67 |
68 | 922 [Sort Array By Parity II](https://leetcode.com/problems/sort-array-by-parity-ii/)
69 | ```python
70 | class Solution(object):
71 | def sortArrayByParityII(self, A):
72 | """
73 | :type A: List[int]
74 | :rtype: List[int]
75 | """
76 | even, odd, length = 0, 1, len(A)
77 | while odd < length and even < length:
78 | if A[even] % 2 != 0 and A[odd] % 2 == 0:
79 | A[even], A[odd] = A[odd], A[even]
80 | odd += 2
81 | even += 2
82 | elif A[even] % 2 != 0 and A[odd] % 2 != 0:
83 | odd += 2
84 | elif A[even] % 2 == 0 and A[odd] % 2 == 0:
85 | even += 2
86 | else:
87 | odd += 2
88 | even += 2
89 | return A
90 | ```
91 |
92 | 929 [Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses)
93 | ```python
94 | class Solution(object):
95 | def numUniqueEmails(self, emails):
96 | """
97 | :type emails: List[str]
98 | :rtype: int
99 | """
100 | ret = {self.simplifyEmail(email): True for email in emails}
101 | return len(ret.keys())
102 |
103 | def simplifyEmail(self, email):
104 | name, domain = email.split('@')
105 | return ''.join(name.split('+')[0].split('.')) + '@' + domain
106 | ```
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Python-LeetCode
2 |
3 | Python-LeetCode 是一个使用 Python 语言解决 LeetCode 问题的代码库,库有以下几个方面需要注意:
4 |
5 | * 所有题目都是 AC 的;
6 |
7 | * 按照题目顺序,每 50 个放在一个目录下,方便查看;
8 |
9 | * 水平所限,无法保证每个题目都是使用的最好的算法;
10 |
11 | * 对于链表和二叉树等结构,会配备测试代码方便本地调试;
12 |
13 | * 部分题目会直接使用 Python 的标准库,比如进行一些别的计算之前,需要先对列表进行排序,这时候可能会直接使用 sort();
14 |
15 | * 部分题目在别的博客中解释了自己的解题思路,可以点击 [这里](./blog) 查看;
16 |
17 | * 库会尽量持续更新,加入更多的题目。
18 |
19 | 如有问题,欢迎指出,一起交流进步!
20 |
21 | 下面是目录的链接
22 |
23 | ## [Problems:1-50](./50)
24 |
25 | ## [Problems:51-100](./100)
26 |
27 | ## [Problems:101-150](./150)
28 |
29 | ## [Problems:151-200](./200)
30 |
31 | ## [Problems:201-250](./250)
32 |
33 | ## [Problems:251-300](./300)
34 |
35 | ## [Problems:301-350](./350)
36 |
37 | ## [Problems:351-400](./400)
38 |
39 | ## [Problems:401-450](./450)
40 |
41 | ## [Problems:451-500](./500)
42 |
43 | ## [Problems:501-550](./550)
44 |
45 | ## [Problems:551-600](./600)
46 |
47 | ## [Problems:601-650](./650)
48 |
49 | ## [Problems:651-700](./700)
50 |
51 | ## [Problems:701-750](./750)
52 |
53 | ## [Problems:751-800](./800)
54 |
55 |
--------------------------------------------------------------------------------
/blog/382.md:
--------------------------------------------------------------------------------
1 | ### [返回单链表的随机节点的值](https://leetcode.com/problems/linked-list-random-node/description/)
2 |
3 | > 额外条件:链表不为空
4 |
5 | > 要求:每个节点的值返回的概率相等
6 | >
7 | > 补充要求:不要使用额外的空间
8 |
9 | ### 思路
10 | 看到题目,在不考虑补充条件的情况下,第一印象是读取一遍链表,并把链表的值存放在一个列表中,然后从列表中随机取出一个值,这种情况只需要遍历一遍链表就可以了,初始化的时候时间复杂度是 O(n),空间复杂度也是 O(n),获取随机值的时候的时间复杂度是 O(1),代码示例如下:
11 |
12 | ```python
13 | class Solution(object):
14 |
15 | def __init__(self, head):
16 | """
17 | @param head The linked list's head.
18 | Note that the head is guaranteed to be not null, so it contains at least one node.
19 | :type head: ListNode
20 | """
21 | self.value = self.get_values(head)
22 |
23 | def get_values(self, head):
24 | value = []
25 | while head:
26 | value.append(head.val)
27 | head = head.next
28 | print value
29 | return value
30 |
31 |
32 | def getRandom(self):
33 | """
34 | Returns a random node's value.
35 | :rtype: int
36 | """
37 | import random
38 | return random.choice(self.value)
39 | ```
40 |
41 | 不过考虑到题目补充条件不能使用额外的空间,这时候只能用时间换空间,也就是说先获取到链表的长度,然后从 0 到链表的长度中随机取出一个数,遍历链表,直到取出的数的值为 0。这种情况的初始化的时候时间复杂度是 O(n),空间复杂度是 O(1),获取随机值的时候时间复杂度是 O(n),代码如下:
42 |
43 | ```python
44 | class Solution(object):
45 | def __init__(self, head):
46 | """
47 | @param head The linked list's head.
48 | Note that the head is guaranteed to be not null, so it contains at least one node.
49 | :type head: ListNode
50 | """
51 | self.head = head
52 | self.length = self.get_length()
53 |
54 | def get_length(self):
55 | length, head = 0, self.head
56 | while head:
57 | length += 1
58 | head = head.next
59 | return length
60 |
61 | def getRandom(self):
62 | """
63 | Returns a random node's value.
64 | :rtype: int
65 | """
66 | import random
67 | num = random.choice(range(0, self.length))
68 | head = self.head
69 | while num:
70 | head = head.next
71 | num -= 1
72 | return head.val
73 | ```
74 |
75 | 注意:使用的 random 并不是真正的完全随机。
76 |
--------------------------------------------------------------------------------
/blog/README.md:
--------------------------------------------------------------------------------
1 | # 目录
2 |
3 | 382 [返回单链表中随机节点的值](./382.md)
4 |
--------------------------------------------------------------------------------
/tests/tree.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # coding=utf-8
3 |
4 | from collections import deque
5 |
6 |
7 | class TreeNode(object):
8 | def __init__(self, x):
9 | self.val = x
10 | self.left = None
11 | self.right = None
12 |
13 |
14 | class Tree(object):
15 | def __init__(self):
16 | self.root = None
17 |
18 | def construct_tree(self, values=None):
19 | """
20 | :param values: list
21 | :return:
22 | """
23 | if not values:
24 | return None
25 | self.root = TreeNode(values[0])
26 | queue = deque([self.root])
27 | leng = len(values)
28 | nums = 1
29 | while nums < leng:
30 | node = queue.popleft()
31 | if node:
32 | node.left = TreeNode(values[nums]) if values[nums] else None
33 | queue.append(node.left)
34 | if nums + 1 < leng:
35 | node.right = TreeNode(values[nums + 1]) if values[nums + 1] else None
36 | queue.append(node.right)
37 | nums += 1
38 | nums += 1
39 |
40 | def bfs(self):
41 | ret = []
42 | queue = deque([self.root])
43 | while queue:
44 | node = queue.popleft()
45 | if node:
46 | ret.append(node.val)
47 | queue.append(node.left)
48 | queue.append(node.right)
49 | return ret
50 |
51 | def pre_traversal(self):
52 | ret = []
53 |
54 | def traversal(head):
55 | if not head:
56 | return
57 | ret.append(head.val)
58 | traversal(head.left)
59 | traversal(head.right)
60 |
61 | traversal(self.root)
62 | return ret
63 |
64 | def in_traversal(self):
65 | ret = []
66 |
67 | def traversal(head):
68 | if not head:
69 | return
70 | traversal(head.left)
71 | ret.append(head.val)
72 | traversal(head.right)
73 |
74 | traversal(self.root)
75 | return ret
76 |
77 | def post_traversal(self):
78 | ret = []
79 |
80 | def traversal(head):
81 | if not head:
82 | return
83 | traversal(head.left)
84 | traversal(head.right)
85 | ret.append(head.val)
86 |
87 | traversal(self.root)
88 | return ret
89 |
90 |
91 | t = Tree()
92 | t.construct_tree([1, 2, None, 4, 3, None, 5])
93 | print t.bfs()
94 | print t.pre_traversal()
95 | print t.in_traversal()
96 | print t.post_traversal()
97 |
--------------------------------------------------------------------------------