0%

leetcode contest 24 solution

好久没刷题拉。。比赛竟然已经到24了。。。- - 题目500+了可怕

本次是contest 24的题解,按题目编号升序排列如下:

    1. Convert BST to Greater Tree
    1. 01 Matrix
    1. Diameter of Binary Tree
    1. Output Contest Matches ### leetcode 538. Convert BST to Greater Tree

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Example:

1
2
3
4
5
6
7
8
9
Input: The root of a Binary Search Tree like this:
5
/ \
2 13

Output: The root of a Greater Tree like this:
18
/ \
20 13

BST中序遍历为升序的,因为先左子树然后中间节点,然后右子树,

这里先右子树然后中间然后左子树,累加右边的即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution(object):
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""

def dfs(root, val):
if not root: return val
right = dfs(root.right, val)
root.val += right
left = dfs(root.left, root.val)
return left

dfs(root, 0)
return root

 

leetcode 542. 01 Matrix

iven a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1: Input:

1
2
3
0 0 0
0 1 0
0 0 0

Output:

1
2
3
0 0 0
0 1 0
0 0 0

Example 2: Input:

1
2
3
0 0 0
0 1 0
1 1 1

Output:

1
2
3
0 0 0
0 1 0
1 2 1

Note:

  1. The number of elements of the given matrix will not exceed 10,000.
  2. There are at least one 0 in the given matrix.
  3. The cells are adjacent in only four directions: up, down, left and right.

DP,设dp[i][j]为最小距离,从左上角到右下角跑一次,然后从右下角到左上角跑一次即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix: return [[]]
m, n = len(matrix), len(matrix[0])
dp = [[0x7fffffff if matrix[i][j] != 0 else 0 for j in range(n)] for i in range(m)]
for i in range(m):
for j in range(n):
self.DP(i, j, m, n, dp)

for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
self.DP(i, j, m, n, dp)

return dp

def DP(self, i, j, m, n, dp):
if i > 0: dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1)
if j > 0: dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1)
if i < m - 1: dp[i][j] = min(dp[i][j], dp[i + 1][j] + 1)
if j < n - 1: dp[i][j] = min(dp[i][j], dp[i][j + 1] + 1)

Java 版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution {
public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) {
if (matrix.size() == 0) return null;
int m = matrix.size(), n = matrix.get(0).size();
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (matrix.get(i).get(j) != 0)
dp[i][j] = Integer.MAX_VALUE - 1;

for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
DP(i, j, m, n, dp);

for (int i = m - 1; i >= 0; i--)
for (int j = n - 1; j >= 0; j--)
DP(i, j, m, n, dp);

List<List<Integer>> ans = new LinkedList<>();
for (int i = 0; i < m; i++) {
List<Integer> cur = new LinkedList<>();
for (int j = 0; j < n; j++)
cur.add(dp[i][j]);
ans.add(cur);
}
return ans;
}

private void DP(int i, int j, int m, int n, int[][] dp) {
if (i > 0) dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + 1);
if (j > 0) dp[i][j] = Math.min(dp[i][j], dp[i][j - 1] + 1);
if (i < m - 1) dp[i][j] = Math.min(dp[i][j], dp[i + 1][j] + 1);
if (j < n - 1) dp[i][j] = Math.min(dp[i][j], dp[i][j + 1] + 1);
}
}

 

leetcode 543. Diameter of Binary Tree

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example: Given a binary tree

1
2
3
4
5
    1
/ \
2 3
/ \
4 5

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

题目地址:

这题直接DFS即可。。

左边的长度+右边的。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
self.ans = 0

def dfs(root, cur):
if not root: return cur - 1
left = dfs(root.left, cur + 1)
right = dfs(root.right, cur + 1)
self.ans = max(self.ans, left - cur + right - cur)
return max(left, right)

dfs(root, 0)
return self.ans

 

leetcode 544. Output Contest Matches

During the NBA playoffs, we always arrange the rather strong team to play with the rather weak team, like make the rank 1 team play with the rank nth team, which is a good strategy to make the contest more interesting. Now, you're given n teams, you need to output their final contest matches in the form of a string.

The n teams are given in the form of positive integers from 1 to n, which represents their initial rank. (Rank 1 is the strongest team and Rank n is the weakest team.) We'll use parentheses('(', ')') and commas(',') to represent the contest team pairing - parentheses('(' , ')') for pairing and commas(',') for partition. During the pairing process in each round, you always need to follow the strategy of making the rather strong one pair with the rather weak one.

Example 1:

1
2
3
4
5
Input: 2
Output: (1,2)
Explanation:
Initially, we have the team 1 and the team 2, placed like: 1,2.
Then we pair the team (1,2) together with '(', ')' and ',', which is the final answer.

Example 2:

1
2
3
4
5
6
7
Input: 4
Output: ((1,4),(2,3))
Explanation:
In the first round, we pair the team 1 and 4, the team 2 and 3 together, as we need to make the strong team and weak team together.
And we got (1,4),(2,3).
In the second round, the winners of (1,4) and (2,3) need to play again to generate the final winner, so you need to add the paratheses outside them.
And we got the final answer ((1,4),(2,3)).

Example 3:

1
2
3
4
5
6
7
Input: 8
Output: (((1,8),(4,5)),((2,7),(3,6)))
Explanation:
First round: (1,8),(2,7),(3,6),(4,5)
Second round: ((1,8),(4,5)),((2,7),(3,6))
Third round: (((1,8),(4,5)),((2,7),(3,6)))
Since the third round will generate the final winner, you need to output the answer (((1,8),(4,5)),((2,7),(3,6))).

Note:

  1. The n is in range [2, 212].
  2. We ensure that the input n can be converted into the form 2k, where k is a positive integer.

每次把第一个队和最后一个队放在一起即可。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def findContestMatch(self, n):
"""
:type n: int
:rtype: str
"""
div = [i + 1 for i in range(n)]
k = int(math.log(n, 2))
for _ in range(k):
t = []
m = len(div)
for i in range(m >> 1):
t.append('(' + str(div[i]) + ',' + str(div[m - i - 1]) + ')')
div = t
return div[0]

 

本次是 leetcode 如下的题解

    1. Convert BST to Greater Tree
    1. 01 Matrix
    1. Diameter of Binary Tree
    1. Output Contest Matches

更多题解可以查看:https://www.hrwhisper.me/leetcode-algorithm-solution/

请我喝杯咖啡吧~