Skip to content

Commit ec1c5a1

Browse files
committed
easy02
1 parent 7cef971 commit ec1c5a1

12 files changed

+426
-2
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
3+
Given a binary tree, find its maximum depth.
4+
5+
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
6+
7+
8+
"""
9+
10+
"""my solution 递归的方式"""
11+
12+
# Definition for a binary tree node.
13+
# class TreeNode(object):
14+
# def __init__(self, x):
15+
# self.val = x
16+
# self.left = None
17+
# self.right = None
18+
19+
class Solution(object):
20+
def maxDepth(self, root):
21+
"""
22+
:type root: TreeNode
23+
:rtype: int
24+
"""
25+
if not root:
26+
return 0
27+
else:
28+
leftmax = self.maxDepth(root.left)+1
29+
rightmax = self.maxDepth(root.right)+1
30+
return max(leftmax,rightmax)
31+
32+
"""other solution
33+
将我的思想转化为一行,巧妙利用了map函数
34+
"""
35+
36+
def maxDepth(self, root):
37+
return 1 + max(map(self.maxDepth, (root.left, root.right))) if root else 0
38+
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""
2+
3+
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
4+
5+
For example:
6+
Given binary tree [3,9,20,null,null,15,7],
7+
3
8+
/ \
9+
9 20
10+
/ \
11+
15 7
12+
return its bottom-up level order traversal as:
13+
[
14+
[15,7],
15+
[9,20],
16+
[3]
17+
]
18+
19+
20+
"""
21+
import collections
22+
"""solution1 : stack + dfs
23+
利用栈来进行存储深度优先搜索需要遍历的节点,注意压入栈的时候要先压入右节点,再压入左节点
24+
这样才能做到先访问左节点
25+
"""
26+
27+
# Definition for a binary tree node.
28+
# class TreeNode(object):
29+
# def __init__(self, x):
30+
# self.val = x
31+
# self.left = None
32+
# self.right = None
33+
34+
class Solution(object):
35+
def levelOrderBottom(self, root):
36+
"""
37+
:type root: TreeNode
38+
:rtype: List[List[int]]
39+
"""
40+
stack = [(root,0)]
41+
res = []
42+
while stack!=[]:
43+
node,level = stack.pop()
44+
if node:
45+
if len(res) < (level+1):
46+
res.insert(0,[])
47+
res[-(level+1)].append(node.val)
48+
stack.append((node.right,level+1))
49+
stack.append((node.left,level+1))
50+
return res
51+
52+
"""solution2 利用队列
53+
54+
"""
55+
56+
def levelOrderBottom(self, root):
57+
queue, res = collections.deque([(root, 0)]), []
58+
while queue:
59+
node, level = queue.popleft()
60+
if node:
61+
if len(res) < level+1:
62+
res.insert(0, [])
63+
res[-(level+1)].append(node.val)
64+
queue.append((node.left, level+1))
65+
queue.append((node.right, level+1))
66+
return res
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"""
2+
3+
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
4+
5+
"""
6+
"""
7+
8+
AVL tree 是一种特殊的二叉查找树,,首先我们要在树中引入平衡因子balance,
9+
表示结点右子树的高度减去左子树的高度差(右-左),对于一棵AVL树要么它是一棵空树,
10+
要么它是一棵高度平衡的二叉查找树,平衡因子balance绝对值不超过1
11+
12+
"""
13+
# Definition for a binary tree node.
14+
# class TreeNode(object):
15+
# def __init__(self, x):
16+
# self.val = x
17+
# self.left = None
18+
# self.right = None
19+
20+
class Solution(object):
21+
def sortedArrayToBST(self, nums):
22+
"""
23+
:type nums: List[int]
24+
:rtype: TreeNode
25+
"""
26+
if not nums:
27+
return None
28+
else:
29+
mid = len(nums)/2
30+
root = TreeNode(nums[mid])
31+
root.left = self.sortedArrayToBST(nums[:mid])
32+
root.right = self.sortedArrayToBST(nums[mid+1:])
33+
return root

easy/112_Path Sum.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
3+
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
4+
5+
For example:
6+
Given the below binary tree and sum = 22,
7+
5
8+
/ \
9+
4 8
10+
/ / \
11+
11 13 4
12+
/ \ \
13+
7 2 1
14+
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
15+
16+
"""
17+
18+
19+
"""my solution
20+
使用递归的思想,首先判断节点是否为空,然后判断是否到了叶子节点,如果不是叶子结点,继续往下走
21+
"""
22+
23+
# Definition for a binary tree node.
24+
# class TreeNode(object):
25+
# def __init__(self, x):
26+
# self.val = x
27+
# self.left = None
28+
# self.right = None
29+
30+
class Solution(object):
31+
def hasPathSum(self, root, sum):
32+
"""
33+
:type root: TreeNode
34+
:type sum: int
35+
:rtype: bool
36+
"""
37+
if not root:
38+
return False
39+
if root.left == None and root.right == None:
40+
return root.val==sum
41+
return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val)

easy/118_Pascal's Triangle.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
3+
Given numRows, generate the first numRows of Pascal's triangle.
4+
5+
For example, given numRows = 5,
6+
Return
7+
8+
[
9+
[1],
10+
[1,1],
11+
[1,2,1],
12+
[1,3,3,1],
13+
[1,4,6,4,1]
14+
]
15+
16+
"""
17+
18+
"""my solution
19+
暴力循环
20+
"""
21+
22+
class Solution(object):
23+
def generate(self, numRows):
24+
"""
25+
:type numRows: int
26+
:rtype: List[List[int]]
27+
"""
28+
if numRows == 0:
29+
return []
30+
elif numRows == 1:
31+
return [[1]]
32+
elif numRows == 2:
33+
return [[1],[1,1]]
34+
else:
35+
rows = [[1],[1,1]]
36+
for i in range(3,numRows+1):
37+
singlerow = []
38+
for j in range(i):
39+
if j == 0 or j == i-1:
40+
singlerow.append(1)
41+
else:
42+
singlerow.append(rows[i-2][j-1]+rows[i-2][j])
43+
rows.append(singlerow)
44+
return rows
45+
46+
"""other solution
47+
为什么append不行
48+
"""
49+
50+
51+
def generate(self, numRows):
52+
res = [[1]]
53+
for i in range(1, numRows):
54+
res += [map(lambda x, y: x + y, res[-1] + [0], [0] + res[-1])]
55+
return res[:numRows]

easy/119_Pascal's Triangle II.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
3+
Given an index k, return the kth row of the Pascal's triangle.
4+
5+
For example, given k = 3,
6+
Return [1,3,3,1].
7+
8+
Note:
9+
Could you optimize your algorithm to use only O(k) extra space?
10+
11+
"""
12+
13+
"""my solution
14+
这里要提醒一下map函数的应用,map在python2中返回的是一个list,而在python3中返回的是一个map object,必须加一个list来进行类型转换
15+
"""
16+
17+
class Solution(object):
18+
def getRow(self, rowIndex):
19+
"""
20+
:type rowIndex: int
21+
:rtype: List[int]
22+
"""
23+
res = [1]
24+
for i in range(1,rowIndex+1):
25+
res = list(map(lambda x,y:x+y,res+[0],[0]+res))
26+
return res
27+
28+
"""other solution
29+
非常类似
30+
"""
31+
32+
class Solution(object):
33+
def getRow(self, rowIndex):
34+
"""
35+
:type rowIndex: int
36+
:rtype: List[int]
37+
"""
38+
row = [1]
39+
for _ in range(rowIndex):
40+
row = [x + y for x, y in zip([0]+row, row+[0])]
41+
return row
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
3+
Say you have an array for which the ith element is the price of a given stock on day i.
4+
5+
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
6+
7+
Example 1:
8+
Input: [7, 1, 5, 3, 6, 4]
9+
Output: 5
10+
11+
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
12+
Example 2:
13+
Input: [7, 6, 4, 3, 1]
14+
Output: 0
15+
16+
In this case, no transaction is done, i.e. max profit = 0.
17+
18+
"""
19+
20+
"""my solution
21+
直接超时
22+
"""
23+
class Solution(object):
24+
def maxProfit(self, prices):
25+
"""
26+
:type prices: List[int]
27+
:rtype: int
28+
"""
29+
max = 0
30+
for i in range(0,len(prices)-1):
31+
for j in range(i+1,len(prices)):
32+
if prices[j] - prices[i] > max:
33+
max = prices[j] - prices[i]
34+
return max
35+
36+
"""
37+
Kadane's Algorithm
38+
"""
39+
40+
class Solution(object):
41+
def maxProfit(self, prices):
42+
"""
43+
:type prices: List[int]
44+
:rtype: int
45+
"""
46+
maxCur = maxSoFar = 0
47+
for i in range(1,len(prices)):
48+
maxCur+=(prices[i]-prices[i-1])
49+
maxCur = max(0,maxCur)
50+
maxSoFar = max(maxCur,maxSoFar)
51+
return maxSoFar
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"""
2+
3+
Say you have an array for which the ith element is the price of a given stock on day i.
4+
5+
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
6+
7+
"""
8+
9+
class Solution(object):
10+
def maxProfit(self, prices):
11+
"""
12+
:type prices: List[int]
13+
:rtype: int
14+
"""
15+
return sum(max(prices[i+1]-prices[i],0) for i in range(len(prices)-1))

easy/125_Valid Palindrome.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
3+
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
4+
5+
For example,
6+
"A man, a plan, a canal: Panama" is a palindrome.
7+
"race a car" is not a palindrome.
8+
9+
Note:
10+
Have you consider that the string might be empty? This is a good question to ask during an interview.
11+
12+
For the purpose of this problem, we define empty string as valid palindrome.
13+
14+
"""
15+
"""
16+
两个指针,用isalnum判断是否是字母,注意统一转换成小写然后再比较
17+
"""
18+
19+
class Solution(object):
20+
def isPalindrome(self, s):
21+
"""
22+
:type s: str
23+
:rtype: bool
24+
"""
25+
if not s:
26+
return True
27+
else:
28+
i = 0
29+
j = len(s) - 1
30+
while i < j:
31+
while i < j and not s[i].isalnum():
32+
i = i + 1
33+
while i < j and not s[j].isalnum():
34+
j = j - 1
35+
if s[i].lower() != s[j].lower():
36+
return False
37+
i = i + 1
38+
j = j - 1
39+
return True

0 commit comments

Comments
 (0)