Description
You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.
A route’s effort is the maximum absolute difference in heights between two consecutive cells of the route.
Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
Example 1:
Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.
Example 2:
Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].
Example 3:
Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
Output: 0
Explanation: This route does not require any effort.
Constraints:
- rows == heights.length
- columns == heights[i].length
- 1 <= rows, columns <= 100
- 1 <= heights[i][j] <= 106
分析
题目的意思是:用最小的代价从左上角到右下角,其中代价是指走的路径中相邻两个格子之间的最大差值。这道题我参考了一下别人的思路,用的是二分法,首先给定一个代价x,然后看它否从左上角走到右下角,如果能,则继续缩小直到找到最小的代价为止,如果不能则代价放大。
代码
class Solution:
def solve(self,mid,m,n,heights):
q=collections.deque()
visited=[[False]*n for _ in range(m)]
q.append((0,0))
visited[0][0]=True
dirs=[[0,1],[0,-1],[1,0],[-1,0]]
while(q):
i,j=q.popleft()
if(i==m-1 and j==n-1):
return True
for d in dirs:
x=i+d[0]
y=j+d[1]
if(x>=0 and x<m and y>=0 and y<n and not visited[x][y]):
diff=abs(heights[x][y]-heights[i][j])
if(diff<=mid):
q.append((x,y))
visited[x][y]=True
return False
def minimumEffortPath(self, heights: List[List[int]]) -> int:
m=len(heights)
n=len(heights[0])
l=0
h=10**6
while(l<h):
mid=l+(h-l)//2
if(self.solve(mid,m,n,heights)):
h=mid
else:
l=mid+1
return l
参考文献
[LeetCode] Leetcode 1631 Path With Minimum Effort (python)
leetcode_company_wise_questions. https://github.com/MysteryVaibhav/leetcode_company_wise_questions
Description
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
分析
题目的意思是:这道题要用队列来实现,以前用C++实现过一次,用python还写了几个bug,哈哈哈,看来不复习迟早会出事。
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if(root is None):
return []
q = deque()
q.append(root)
res=[]
while(q):
t=[]
for _ in range(len(q)):
p=q.popleft()
t.append(p.val)
if(p.left):
q.append(p.left)
if(p.right):
q.append(p.right)
res.append(t)
return res