leetcode contest 24 solution

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

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

  • 538. Convert BST to Greater Tree
  • 542. 01 Matrix
  • 543. Diameter of Binary Tree
  • 544. 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:

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

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

 

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:

Output:

Example 2:
Input:

Output:

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]为最小距离,从左上角到右下角跑一次,然后从右下角到左上角跑一次即可

Java 版本

 

 

 

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

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

题目地址:

这题直接DFS即可。。

左边的长度+右边的。。

 

 

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:

Example 2:

Example 3:

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.

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

 

 

本次是 leetcode 如下的题解

  • 538. Convert BST to Greater Tree
  • 542. 01 Matrix
  • 543. Diameter of Binary Tree
  • 544. Output Contest Matches

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

本博客若无特殊说明则由 hrwhisper 原创发布
转载请点名出处:细语呢喃 > leetcode contest 24 solution
本文地址:https://www.hrwhisper.me/leetcode-contest-24-solution/

听说帅的人已经打赏了

Leetcode . permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *