Skip to content

Commit 79e6e76

Browse files
committed
数组中等题
1 parent 8e4aac0 commit 79e6e76

File tree

62 files changed

+2393
-1
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

62 files changed

+2393
-1
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
"""使用53题的思路,两个变量"""
20+
21+
class Solution(object):
22+
def maxProfit(self, prices):
23+
"""
24+
:type prices: List[int]
25+
:rtype: int
26+
"""
27+
curSum=maxSum=0
28+
for i in range(1,len(prices)):
29+
curSum=max(0,curSum+prices[i]-prices[i-1])
30+
maxSum = max(curSum,maxSum)
31+
return maxSum
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
3+
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
4+
5+
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
6+
7+
Credits:
8+
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
9+
10+
"""
11+
"""动态规划
12+
f(0) = nums[0]
13+
f(1) = max(num[0], num[1])
14+
f(k) = max( f(k-2) + nums[k], f(k-1) )
15+
16+
"""
17+
18+
class Solution(object):
19+
def rob(self, nums):
20+
"""
21+
:type nums: List[int]
22+
:rtype: int
23+
"""
24+
if not nums:
25+
return 0
26+
if len(nums) < 3:
27+
return max(nums)
28+
else:
29+
nums[1] = max(nums[0],nums[1])
30+
for i in range(2,len(nums)):
31+
nums[i] = max(nums[i]+nums[i-2],nums[i-1])
32+
return nums[-1]
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
3+
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
4+
5+
Example:
6+
Given nums = [-2, 0, 3, -5, 2, -1]
7+
8+
sumRange(0, 2) -> 1
9+
sumRange(2, 5) -> -1
10+
sumRange(0, 5) -> -3
11+
Note:
12+
You may assume that the array does not change.
13+
There are many calls to sumRange function.
14+
15+
16+
"""
17+
18+
"""正向思维,用一个数组保存从第一个数到每个位置的求和"""
19+
20+
21+
class NumArray(object):
22+
def __init__(self, nums):
23+
"""
24+
:type nums: List[int]
25+
"""
26+
self.dp = nums
27+
for i in range(1, len(nums)):
28+
self.dp[i] += self.dp[i - 1]
29+
30+
def sumRange(self, i, j):
31+
"""
32+
:type i: int
33+
:type j: int
34+
:rtype: int
35+
"""
36+
return self.dp[j] - (self.dp[i - 1] if i > 0 else 0)
37+
38+
39+
40+
41+
# Your NumArray object will be instantiated and called as such:
42+
# obj = NumArray(nums)
43+
# param_1 = obj.sumRange(i,j)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
3+
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
4+
5+
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
6+
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
7+
8+
click to show more practice.
9+
10+
Subscribe to see which companies asked this question.
11+
12+
"""
13+
14+
"""要点:两个指针,一个指针记录当前的最大值a1,一个记录循环每个元素时的最大值a2
15+
a2的更新规则是,如果a2+当前元素比原来a2大,则更新a2=原a2+当前元素,否则a2=当前元素
16+
a1的更新规则是 a1 = a1 if a1 >a2 else a2
17+
"""
18+
19+
class Solution(object):
20+
def maxSubArray(self, nums):
21+
"""
22+
:type nums: List[int]
23+
:rtype: int
24+
"""
25+
curSum=maxSum=nums[0]
26+
for i in range(1,len(nums)):
27+
curSum = max(nums[i],curSum+nums[i])
28+
maxSum = max(curSum,maxSum)
29+
return maxSum
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""
2+
3+
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
4+
5+
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
6+
7+
How many possible unique paths are there?
8+
9+
10+
11+
12+
"""
13+
14+
"""利用数学方法"""
15+
16+
17+
class Solution(object):
18+
def uniquePaths(self, m, n):
19+
"""
20+
:type m: int
21+
:type n: int
22+
:rtype: int
23+
"""
24+
if m > n:
25+
m, n = m - 1, n - 1
26+
else:
27+
m, n = n - 1, m - 1
28+
if m <= 0 or n <= 0:
29+
return 1
30+
t = m + n
31+
sub = 1
32+
for i in range(1, n):
33+
t = t * (m + n - i)
34+
sub = sub * (i + 1)
35+
36+
return t / sub
37+
38+
"""利用动态规划的方法"""
39+
40+
41+
class Solution(object):
42+
def uniquePaths(self, m, n):
43+
"""
44+
:type m: int
45+
:type n: int
46+
:rtype: int
47+
"""
48+
count = [[0 for t in range(n)] for x in range(m)]
49+
count[0][0] = 1
50+
for i in range(m):
51+
for j in range(n):
52+
if i == 0 and j == 0:
53+
count[i][j] = 1
54+
elif i == 0:
55+
count[i][j] = count[i][j - 1]
56+
elif j == 0:
57+
count[i][j] = count[i - 1][j]
58+
else:
59+
count[i][j] = count[i - 1][j] + count[i][j - 1]
60+
return count[m - 1][n - 1]
61+
62+
63+
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
3+
Follow up for "Unique Paths":
4+
5+
Now consider if some obstacles are added to the grids. How many unique paths would there be?
6+
7+
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
8+
9+
For example,
10+
There is one obstacle in the middle of a 3x3 grid as illustrated below.
11+
12+
[
13+
[0,0,0],
14+
[0,1,0],
15+
[0,0,0]
16+
]
17+
The total number of unique paths is 2.
18+
19+
Note: m and n will be at most 100.
20+
21+
"""
22+
"""与62题相似,不过多了一个条件"""
23+
24+
25+
class Solution(object):
26+
def uniquePathsWithObstacles(self, obstacleGrid):
27+
"""
28+
:type obstacleGrid: List[List[int]]
29+
:rtype: int
30+
"""
31+
if not obstacleGrid:
32+
return 0
33+
for i in range(len(obstacleGrid)):
34+
for j in range(len(obstacleGrid[0])):
35+
if obstacleGrid[i][j] == 1:
36+
obstacleGrid[i][j] = 0
37+
elif i == 0 and j == 0:
38+
obstacleGrid[i][j] = 1
39+
elif i == 0:
40+
obstacleGrid[i][j] = obstacleGrid[i][j - 1]
41+
elif j == 0:
42+
obstacleGrid[i][j] = obstacleGrid[i - 1][j]
43+
else:
44+
obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1]
45+
return obstacleGrid[i][j]
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
3+
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
4+
5+
Note: You can only move either down or right at any point in time.
6+
7+
"""
8+
"""仍然是和62题一样的思路"""
9+
class Solution(object):
10+
def minPathSum(self, grid):
11+
"""
12+
:type grid: List[List[int]]
13+
:rtype: int
14+
"""
15+
for i in range(len(grid)-1,-1,-1):
16+
for j in range(len(grid[0])-1,-1,-1):
17+
if j == len(grid[0])-1 and i== len(grid)-1:
18+
continue
19+
elif j == len(grid[0])-1:
20+
grid[i][j] = grid[i+1][j] + grid[i][j]
21+
elif i == len(grid)-1:
22+
grid[i][j] = grid[i][j] + grid[i][j+1]
23+
else:
24+
grid[i][j] = grid[i][j] + min(grid[i+1][j],grid[i][j+1])
25+
return grid[0][0]
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"""
2+
3+
You are climbing a stair case. It takes n steps to reach to the top.
4+
5+
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
6+
7+
Note: Given n will be a positive integer.
8+
9+
"""
10+
"""动态规划的思路,详细解释参照文章开头给出的公众号帖子"""
11+
class Solution(object):
12+
def climbStairs(self, n):
13+
"""
14+
:type n: int
15+
:rtype: int
16+
"""
17+
a = 1
18+
b = 1
19+
for i in range(2,n+1):
20+
a,b = b,a+b
21+
return b
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
3+
Given two binary trees, write a function to check if they are equal or not.
4+
5+
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
6+
7+
"""
8+
"""递归的判断两个数是否相等,并判断两棵树时候同时为空,即结构是否相等"""
9+
10+
# Definition for a binary tree node.
11+
# class TreeNode(object):
12+
# def __init__(self, x):
13+
# self.val = x
14+
# self.left = None
15+
# self.right = None
16+
17+
class Solution(object):
18+
def isSameTree(self, p, q):
19+
"""
20+
:type p: TreeNode
21+
:type q: TreeNode
22+
:rtype: bool
23+
"""
24+
if p and q:
25+
if p.val == q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right):
26+
return True
27+
else:
28+
return False
29+
return p is q
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
# Definition for a binary tree node.
11+
# class TreeNode(object):
12+
# def __init__(self, x):
13+
# self.val = x
14+
# self.left = None
15+
# self.right = None
16+
17+
class Solution(object):
18+
def maxDepth(self, root):
19+
"""
20+
:type root: TreeNode
21+
:rtype: int
22+
"""
23+
if not root:
24+
return 0
25+
left = self.maxDepth(root.left)+1
26+
right = self.maxDepth(root.right)+1
27+
return max(left,right)

0 commit comments

Comments
 (0)