mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-06 01:15:57 +08:00
Update solution 0617 & Add solution 0752
This commit is contained in:
36
README.md
36
README.md
@ -126,16 +126,16 @@
|
||||
|
||||
| | Easy | Medium | Hard | Total |
|
||||
|:--------:|:--------:|:--------:|:--------:|:--------:|
|
||||
|Optimizing|33|31|23|87|
|
||||
|Accepted|**284**|**392**|**115**|**791**|
|
||||
|Optimizing|33|30|23|86|
|
||||
|Accepted|**285**|**392**|**115**|**792**|
|
||||
|Total|501|1010|400|1911|
|
||||
|Perfection Rate|88.4%|92.1%|80.0%|89.0%|
|
||||
|Completion Rate|56.7%|38.8%|28.7%|41.4%|
|
||||
|Perfection Rate|88.4%|92.3%|80.0%|89.1%|
|
||||
|Completion Rate|56.9%|38.8%|28.7%|41.4%|
|
||||
|------------|----------------------------|----------------------------|----------------------------|----------------------------|
|
||||
|
||||
## 二. 目录
|
||||
|
||||
以下已经收录了 704 道题的题解,还有 11 道题在尝试优化到 beats 100%
|
||||
以下已经收录了 706 道题的题解,还有 11 道题在尝试优化到 beats 100%
|
||||
|
||||
| No. | Title | Solution | Acceptance | Difficulty | Frequency |
|
||||
|:--------:|:--------------------------------------------------------------|:--------:|:--------:|:--------:|:--------:|
|
||||
@ -335,7 +335,7 @@
|
||||
|0194|Transpose File||24.5%|Medium||
|
||||
|0195|Tenth Line||32.7%|Easy||
|
||||
|0196|Delete Duplicate Emails||47.2%|Easy||
|
||||
|0197|Rising Temperature||40.7%|Easy||
|
||||
|0197|Rising Temperature||40.6%|Easy||
|
||||
|0198|House Robber|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0198.House-Robber)|43.7%|Medium||
|
||||
|0199|Binary Tree Right Side View|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0199.Binary-Tree-Right-Side-View)|57.1%|Medium||
|
||||
|0200|Number of Islands|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0200.Number-of-Islands)|50.4%|Medium||
|
||||
@ -755,7 +755,7 @@
|
||||
|0614|Second Degree Follower||33.3%|Medium||
|
||||
|0615|Average Salary: Departments VS Company||53.9%|Hard||
|
||||
|0616|Add Bold Tag in String||45.3%|Medium||
|
||||
|0617|Merge Two Binary Trees||76.0%|Easy||
|
||||
|0617|Merge Two Binary Trees|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0617.Merge-Two-Binary-Trees)|76.0%|Easy||
|
||||
|0618|Students Report By Geography||61.5%|Hard||
|
||||
|0619|Biggest Single Number||45.8%|Easy||
|
||||
|0620|Not Boring Movies||70.8%|Easy||
|
||||
@ -890,7 +890,7 @@
|
||||
|0749|Contain Virus||49.0%|Hard||
|
||||
|0750|Number Of Corner Rectangles||67.3%|Medium||
|
||||
|0751|IP to CIDR||58.2%|Medium||
|
||||
|0752|Open the Lock||54.7%|Medium||
|
||||
|0752|Open the Lock|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0752.Open-the-Lock)|54.7%|Medium||
|
||||
|0753|Cracking the Safe|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0753.Cracking-the-Safe)|52.9%|Hard||
|
||||
|0754|Reach a Number||40.7%|Medium||
|
||||
|0755|Pour Water||44.5%|Medium||
|
||||
@ -1494,7 +1494,7 @@
|
||||
|1354|Construct Target Array With Multiple Sums||31.4%|Hard||
|
||||
|1355|Activity Participants||74.7%|Medium||
|
||||
|1356|Sort Integers by The Number of 1 Bits||70.6%|Easy||
|
||||
|1357|Apply Discount Every n Orders||67.2%|Medium||
|
||||
|1357|Apply Discount Every n Orders||67.3%|Medium||
|
||||
|1358|Number of Substrings Containing All Three Characters||61.0%|Medium||
|
||||
|1359|Count All Valid Pickup and Delivery Options||55.7%|Hard||
|
||||
|1360|Number of Days Between Two Dates||46.5%|Easy||
|
||||
@ -1706,7 +1706,7 @@
|
||||
|1566|Detect Pattern of Length M Repeated K or More Times||43.0%|Easy||
|
||||
|1567|Maximum Length of Subarray With Positive Product||37.6%|Medium||
|
||||
|1568|Minimum Number of Days to Disconnect Island||50.1%|Hard||
|
||||
|1569|Number of Ways to Reorder Array to Get Same BST||50.1%|Hard||
|
||||
|1569|Number of Ways to Reorder Array to Get Same BST||50.0%|Hard||
|
||||
|1570|Dot Product of Two Sparse Vectors||91.1%|Medium||
|
||||
|1571|Warehouse Manager||89.6%|Easy||
|
||||
|1572|Matrix Diagonal Sum|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1572.Matrix-Diagonal-Sum)|78.0%|Easy||
|
||||
@ -1911,7 +1911,7 @@
|
||||
|1771|Maximize Palindrome Length From Subsequences||34.4%|Hard||
|
||||
|1772|Sort Features by Popularity||65.5%|Medium||
|
||||
|1773|Count Items Matching a Rule||84.6%|Easy||
|
||||
|1774|Closest Dessert Cost||45.4%|Medium||
|
||||
|1774|Closest Dessert Cost||45.3%|Medium||
|
||||
|1775|Equal Sum Arrays With Minimum Number of Operations||50.5%|Medium||
|
||||
|1776|Car Fleet II||49.9%|Hard||
|
||||
|1777|Product's Price for Each Store||86.3%|Easy||
|
||||
@ -2022,7 +2022,7 @@
|
||||
|1882|Process Tasks Using Servers||30.6%|Medium||
|
||||
|1883|Minimum Skips to Arrive at Meeting On Time||38.2%|Hard||
|
||||
|1884|Egg Drop With 2 Eggs and N Floors||69.9%|Medium||
|
||||
|1885|Count Pairs in Two Arrays||54.8%|Medium||
|
||||
|1885|Count Pairs in Two Arrays||54.9%|Medium||
|
||||
|1886|Determine Whether Matrix Can Be Obtained By Rotation||53.9%|Easy||
|
||||
|1887|Reduction Operations to Make the Array Elements Equal||59.7%|Medium||
|
||||
|1888|Minimum Number of Flips to Make the Binary String Alternating||33.8%|Medium||
|
||||
@ -2033,7 +2033,7 @@
|
||||
|1893|Check if All the Integers in a Range Are Covered||49.1%|Easy||
|
||||
|1894|Find the Student that Will Replace the Chalk||38.6%|Medium||
|
||||
|1895|Largest Magic Square||49.3%|Medium||
|
||||
|1896|Minimum Cost to Change the Final Value of Expression||51.5%|Hard||
|
||||
|1896|Minimum Cost to Change the Final Value of Expression||51.4%|Hard||
|
||||
|1897|Redistribute Characters to Make All Strings Equal||58.6%|Easy||
|
||||
|1898|Maximum Number of Removable Characters||32.3%|Medium||
|
||||
|1899|Merge Triplets to Form Target Triplet||58.9%|Medium||
|
||||
@ -2044,12 +2044,12 @@
|
||||
|1904|The Number of Full Rounds You Have Played||52.6%|Medium||
|
||||
|1905|Count Sub Islands||59.9%|Medium||
|
||||
|1906|Minimum Absolute Difference Queries||41.5%|Medium||
|
||||
|1907|Count Salary Categories||62.1%|Medium||
|
||||
|1907|Count Salary Categories||62.2%|Medium||
|
||||
|1908|Game of Nim||66.8%|Medium||
|
||||
|1909|Remove One Element to Make the Array Strictly Increasing||28.4%|Easy||
|
||||
|1910|Remove All Occurrences of a Substring||70.7%|Medium||
|
||||
|1911|Maximum Alternating Subsequence Sum||52.5%|Medium||
|
||||
|1912|Design Movie Rental System||33.8%|Hard||
|
||||
|1909|Remove One Element to Make the Array Strictly Increasing||28.5%|Easy||
|
||||
|1910|Remove All Occurrences of a Substring||70.8%|Medium||
|
||||
|1911|Maximum Alternating Subsequence Sum||52.6%|Medium||
|
||||
|1912|Design Movie Rental System||33.9%|Hard||
|
||||
|------------|-------------------------------------------------------|-------| ----------------| ---------------|-------------|
|
||||
|
||||
------------------------------------------------------------------
|
||||
|
@ -20,14 +20,11 @@ func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode {
|
||||
if root1 == nil {
|
||||
return root2
|
||||
}
|
||||
|
||||
if root2 == nil {
|
||||
return root1
|
||||
}
|
||||
|
||||
root1.Val += root2.Val
|
||||
root1.Left = mergeTrees(root1.Left, root2.Left)
|
||||
root1.Right = mergeTrees(root1.Right, root2.Right)
|
||||
|
||||
return root1
|
||||
}
|
||||
|
@ -1,30 +1,80 @@
|
||||
# [617. Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
You are given two binary trees **root1** and **root2**.
|
||||
You are given two binary trees `root1` and `root2`.
|
||||
|
||||
Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
|
||||
|
||||
Return the merged tree.
|
||||
Return *the merged tree*.
|
||||
|
||||
**Note**: The merging process must start from the root nodes of both trees.
|
||||
**Note:** The merging process must start from the root nodes of both trees.
|
||||
|
||||
**Example 1**:
|
||||
**Example 1:**
|
||||
|
||||

|
||||
|
||||
```
|
||||
Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
|
||||
Output: [3,4,5,5,4,null,7]
|
||||
```
|
||||
|
||||
**Example 2**:
|
||||
**Example 2:**
|
||||
|
||||
```
|
||||
Input: root1 = [1], root2 = [1,2]
|
||||
Output: [2,2]
|
||||
```
|
||||
|
||||
**Constraints**:
|
||||
**Constraints:**
|
||||
|
||||
1. The number of nodes in both trees is in the range [0, 2000].
|
||||
2. -104 <= Node.val <= 104
|
||||
- The number of nodes in both trees is in the range `[0, 2000]`.
|
||||
- `104 <= Node.val <= 104`
|
||||
|
||||
## 题目大意
|
||||
|
||||
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 简单题。采用深搜的思路,分别从根节点开始同时遍历两个二叉树,并将对应的节点进行合并。两个二叉树的对应节点可能存在以下三种情况:
|
||||
- 如果两个二叉树的对应节点都为空,则合并后的二叉树的对应节点也为空;
|
||||
- 如果两个二叉树的对应节点只有一个为空,则合并后的二叉树的对应节点为其中的非空节点;
|
||||
- 如果两个二叉树的对应节点都不为空,则合并后的二叉树的对应节点的值为两个二叉树的对应节点的值之和,此时需要显性合并两个节点。
|
||||
- 对一个节点进行合并之后,还要对该节点的左右子树分别进行合并。用递归实现即可。
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"github.com/halfrost/LeetCode-Go/structures"
|
||||
)
|
||||
|
||||
// TreeNode define
|
||||
type TreeNode = structures.TreeNode
|
||||
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* type TreeNode struct {
|
||||
* Val int
|
||||
* Left *TreeNode
|
||||
* Right *TreeNode
|
||||
* }
|
||||
*/
|
||||
|
||||
func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode {
|
||||
if root1 == nil {
|
||||
return root2
|
||||
}
|
||||
if root2 == nil {
|
||||
return root1
|
||||
}
|
||||
root1.Val += root2.Val
|
||||
root1.Left = mergeTrees(root1.Left, root2.Left)
|
||||
root1.Right = mergeTrees(root1.Right, root2.Right)
|
||||
return root1
|
||||
}
|
||||
```
|
57
leetcode/0752.Open-the-Lock/752. Open the Lock.go
Normal file
57
leetcode/0752.Open-the-Lock/752. Open the Lock.go
Normal file
@ -0,0 +1,57 @@
|
||||
package leetcode
|
||||
|
||||
func openLock(deadends []string, target string) int {
|
||||
if target == "0000" {
|
||||
return 0
|
||||
}
|
||||
targetNum, visited := strToInt(target), make([]bool, 10000)
|
||||
visited[0] = true
|
||||
for _, deadend := range deadends {
|
||||
num := strToInt(deadend)
|
||||
if num == 0 {
|
||||
return -1
|
||||
}
|
||||
visited[num] = true
|
||||
}
|
||||
depth, curDepth, nextDepth := 0, []int16{0}, make([]int16, 0)
|
||||
var nextNum int16
|
||||
for len(curDepth) > 0 {
|
||||
nextDepth = nextDepth[0:0]
|
||||
for _, curNum := range curDepth {
|
||||
for incrementer := int16(1000); incrementer > 0; incrementer /= 10 {
|
||||
digit := (curNum / incrementer) % 10
|
||||
if digit == 9 {
|
||||
nextNum = curNum - 9*incrementer
|
||||
} else {
|
||||
nextNum = curNum + incrementer
|
||||
}
|
||||
if nextNum == targetNum {
|
||||
return depth + 1
|
||||
}
|
||||
if !visited[nextNum] {
|
||||
visited[nextNum] = true
|
||||
nextDepth = append(nextDepth, nextNum)
|
||||
}
|
||||
if digit == 0 {
|
||||
nextNum = curNum + 9*incrementer
|
||||
} else {
|
||||
nextNum = curNum - incrementer
|
||||
}
|
||||
if nextNum == targetNum {
|
||||
return depth + 1
|
||||
}
|
||||
if !visited[nextNum] {
|
||||
visited[nextNum] = true
|
||||
nextDepth = append(nextDepth, nextNum)
|
||||
}
|
||||
}
|
||||
}
|
||||
curDepth, nextDepth = nextDepth, curDepth
|
||||
depth++
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func strToInt(str string) int16 {
|
||||
return int16(str[0]-'0')*1000 + int16(str[1]-'0')*100 + int16(str[2]-'0')*10 + int16(str[3]-'0')
|
||||
}
|
53
leetcode/0752.Open-the-Lock/752. Open the Lock_test.go
Normal file
53
leetcode/0752.Open-the-Lock/752. Open the Lock_test.go
Normal file
@ -0,0 +1,53 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question752 struct {
|
||||
para752
|
||||
ans752
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
// one 代表第一个参数
|
||||
type para752 struct {
|
||||
deadends []string
|
||||
target string
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
// one 代表第一个答案
|
||||
type ans752 struct {
|
||||
one int
|
||||
}
|
||||
|
||||
func Test_Problem752(t *testing.T) {
|
||||
|
||||
qs := []question752{
|
||||
|
||||
{
|
||||
para752{[]string{"0201", "0101", "0102", "1212", "2002"}, "0202"},
|
||||
ans752{6},
|
||||
},
|
||||
|
||||
{
|
||||
para752{[]string{"8888"}, "0009"},
|
||||
ans752{1},
|
||||
},
|
||||
|
||||
{
|
||||
para752{[]string{"8887", "8889", "8878", "8898", "8788", "8988", "7888", "9888"}, "8888"},
|
||||
ans752{-1},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 752------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans752, q.para752
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, openLock(p.deadends, p.target))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
131
leetcode/0752.Open-the-Lock/README.md
Normal file
131
leetcode/0752.Open-the-Lock/README.md
Normal file
@ -0,0 +1,131 @@
|
||||
# [752. Open the Lock](https://leetcode.com/problems/open-the-lock/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot.
|
||||
|
||||
The lock initially starts at `'0000'`, a string representing the state of the 4 wheels.
|
||||
|
||||
You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
|
||||
|
||||
Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
```
|
||||
Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
|
||||
Output: 6
|
||||
Explanation:
|
||||
A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
|
||||
Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
|
||||
because the wheels of the lock become stuck after the display becomes the dead end "0102".
|
||||
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
|
||||
```
|
||||
Input: deadends = ["8888"], target = "0009"
|
||||
Output: 1
|
||||
Explanation:
|
||||
We can turn the last wheel in reverse to move from "0000" -> "0009".
|
||||
|
||||
```
|
||||
|
||||
**Example 3:**
|
||||
|
||||
```
|
||||
Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
|
||||
Output: -1
|
||||
Explanation:
|
||||
We can't reach the target without getting stuck.
|
||||
|
||||
```
|
||||
|
||||
**Example 4:**
|
||||
|
||||
```
|
||||
Input: deadends = ["0000"], target = "8888"
|
||||
Output: -1
|
||||
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- `1 <= deadends.length <= 500`
|
||||
- `deadends[i].length == 4`
|
||||
- `target.length == 4`
|
||||
- target **will not be** in the list `deadends`.
|
||||
- `target` and `deadends[i]` consist of digits only.
|
||||
|
||||
## 题目大意
|
||||
|
||||
你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 。每个拨轮可以自由旋转:例如把 '9' 变为 '0','0' 变为 '9' 。每次旋转都只能旋转一个拨轮的一位数字。锁的初始数字为 '0000' ,一个代表四个拨轮的数字的字符串。列表 deadends 包含了一组死亡数字,一旦拨轮的数字和列表里的任何一个元素相同,这个锁将会被永久锁定,无法再被旋转。字符串 target 代表可以解锁的数字,你需要给出解锁需要的最小旋转次数,如果无论如何不能解锁,返回 -1 。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 此题可以转化为从起始点到终点的最短路径。采用广度优先搜索。每次广搜枚举转动一次数字的状态,并且用 visited 记录是否被搜索过,如果没有被搜索过,便加入队列,下一轮继续搜索。如果搜索到了 target,便返回对应的旋转次数。如果搜索完成后,仍没有搜索到 target,说明无法解锁,返回 -1。特殊情况,如果 target 就是初始数字 0000,那么直接返回答案 0。
|
||||
- 在广搜之前,先将 deadends 放入 map 中,搜索中判断是否搜到了 deadends。如果初始数字 0000 出现在 deadends 中,可以直接返回答案 −1。
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
func openLock(deadends []string, target string) int {
|
||||
if target == "0000" {
|
||||
return 0
|
||||
}
|
||||
targetNum, visited := strToInt(target), make([]bool, 10000)
|
||||
visited[0] = true
|
||||
for _, deadend := range deadends {
|
||||
num := strToInt(deadend)
|
||||
if num == 0 {
|
||||
return -1
|
||||
}
|
||||
visited[num] = true
|
||||
}
|
||||
depth, curDepth, nextDepth := 0, []int16{0}, make([]int16, 0)
|
||||
var nextNum int16
|
||||
for len(curDepth) > 0 {
|
||||
nextDepth = nextDepth[0:0]
|
||||
for _, curNum := range curDepth {
|
||||
for incrementer := int16(1000); incrementer > 0; incrementer /= 10 {
|
||||
digit := (curNum / incrementer) % 10
|
||||
if digit == 9 {
|
||||
nextNum = curNum - 9*incrementer
|
||||
} else {
|
||||
nextNum = curNum + incrementer
|
||||
}
|
||||
if nextNum == targetNum {
|
||||
return depth + 1
|
||||
}
|
||||
if !visited[nextNum] {
|
||||
visited[nextNum] = true
|
||||
nextDepth = append(nextDepth, nextNum)
|
||||
}
|
||||
if digit == 0 {
|
||||
nextNum = curNum + 9*incrementer
|
||||
} else {
|
||||
nextNum = curNum - incrementer
|
||||
}
|
||||
if nextNum == targetNum {
|
||||
return depth + 1
|
||||
}
|
||||
if !visited[nextNum] {
|
||||
visited[nextNum] = true
|
||||
nextDepth = append(nextDepth, nextNum)
|
||||
}
|
||||
}
|
||||
}
|
||||
curDepth, nextDepth = nextDepth, curDepth
|
||||
depth++
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func strToInt(str string) int16 {
|
||||
return int16(str[0]-'0')*1000 + int16(str[1]-'0')*100 + int16(str[2]-'0')*10 + int16(str[3]-'0')
|
||||
}
|
||||
```
|
@ -96,5 +96,5 @@ func findDuplicate(paths []string) [][]string {
|
||||
----------------------------------------------
|
||||
<div style="display: flex;justify-content: space-between;align-items: center;">
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0600~0699/0605.Can-Place-Flowers/">⬅️上一页</a></p>
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0600~0699/0622.Design-Circular-Queue/">下一页➡️</a></p>
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0600~0699/0617.Merge-Two-Binary-Trees/">下一页➡️</a></p>
|
||||
</div>
|
||||
|
@ -0,0 +1,87 @@
|
||||
# [617. Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
You are given two binary trees `root1` and `root2`.
|
||||
|
||||
Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
|
||||
|
||||
Return *the merged tree*.
|
||||
|
||||
**Note:** The merging process must start from the root nodes of both trees.
|
||||
|
||||
**Example 1:**
|
||||
|
||||

|
||||
|
||||
```
|
||||
Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
|
||||
Output: [3,4,5,5,4,null,7]
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
|
||||
```
|
||||
Input: root1 = [1], root2 = [1,2]
|
||||
Output: [2,2]
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- The number of nodes in both trees is in the range `[0, 2000]`.
|
||||
- `104 <= Node.val <= 104`
|
||||
|
||||
## 题目大意
|
||||
|
||||
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 简单题。采用深搜的思路,分别从根节点开始同时遍历两个二叉树,并将对应的节点进行合并。两个二叉树的对应节点可能存在以下三种情况:
|
||||
- 如果两个二叉树的对应节点都为空,则合并后的二叉树的对应节点也为空;
|
||||
- 如果两个二叉树的对应节点只有一个为空,则合并后的二叉树的对应节点为其中的非空节点;
|
||||
- 如果两个二叉树的对应节点都不为空,则合并后的二叉树的对应节点的值为两个二叉树的对应节点的值之和,此时需要显性合并两个节点。
|
||||
- 对一个节点进行合并之后,还要对该节点的左右子树分别进行合并。用递归实现即可。
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"github.com/halfrost/LeetCode-Go/structures"
|
||||
)
|
||||
|
||||
// TreeNode define
|
||||
type TreeNode = structures.TreeNode
|
||||
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* type TreeNode struct {
|
||||
* Val int
|
||||
* Left *TreeNode
|
||||
* Right *TreeNode
|
||||
* }
|
||||
*/
|
||||
|
||||
func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode {
|
||||
if root1 == nil {
|
||||
return root2
|
||||
}
|
||||
if root2 == nil {
|
||||
return root1
|
||||
}
|
||||
root1.Val += root2.Val
|
||||
root1.Left = mergeTrees(root1.Left, root2.Left)
|
||||
root1.Right = mergeTrees(root1.Right, root2.Right)
|
||||
return root1
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
----------------------------------------------
|
||||
<div style="display: flex;justify-content: space-between;align-items: center;">
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0600~0699/0609.Find-Duplicate-File-in-System/">⬅️上一页</a></p>
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0600~0699/0622.Design-Circular-Queue/">下一页➡️</a></p>
|
||||
</div>
|
@ -149,6 +149,6 @@ func (this *MyCircularQueue) IsFull() bool {
|
||||
|
||||
----------------------------------------------
|
||||
<div style="display: flex;justify-content: space-between;align-items: center;">
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0600~0699/0609.Find-Duplicate-File-in-System/">⬅️上一页</a></p>
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0600~0699/0617.Merge-Two-Binary-Trees/">⬅️上一页</a></p>
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0600~0699/0623.Add-One-Row-to-Tree/">下一页➡️</a></p>
|
||||
</div>
|
||||
|
@ -105,5 +105,5 @@ func match(lp [26]int, w string) bool {
|
||||
----------------------------------------------
|
||||
<div style="display: flex;justify-content: space-between;align-items: center;">
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0746.Min-Cost-Climbing-Stairs/">⬅️上一页</a></p>
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0753.Cracking-the-Safe/">下一页➡️</a></p>
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0752.Open-the-Lock/">下一页➡️</a></p>
|
||||
</div>
|
||||
|
138
website/content/ChapterFour/0700~0799/0752.Open-the-Lock.md
Normal file
138
website/content/ChapterFour/0700~0799/0752.Open-the-Lock.md
Normal file
@ -0,0 +1,138 @@
|
||||
# [752. Open the Lock](https://leetcode.com/problems/open-the-lock/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot.
|
||||
|
||||
The lock initially starts at `'0000'`, a string representing the state of the 4 wheels.
|
||||
|
||||
You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
|
||||
|
||||
Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
```
|
||||
Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
|
||||
Output: 6
|
||||
Explanation:
|
||||
A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
|
||||
Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
|
||||
because the wheels of the lock become stuck after the display becomes the dead end "0102".
|
||||
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
|
||||
```
|
||||
Input: deadends = ["8888"], target = "0009"
|
||||
Output: 1
|
||||
Explanation:
|
||||
We can turn the last wheel in reverse to move from "0000" -> "0009".
|
||||
|
||||
```
|
||||
|
||||
**Example 3:**
|
||||
|
||||
```
|
||||
Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
|
||||
Output: -1
|
||||
Explanation:
|
||||
We can't reach the target without getting stuck.
|
||||
|
||||
```
|
||||
|
||||
**Example 4:**
|
||||
|
||||
```
|
||||
Input: deadends = ["0000"], target = "8888"
|
||||
Output: -1
|
||||
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- `1 <= deadends.length <= 500`
|
||||
- `deadends[i].length == 4`
|
||||
- `target.length == 4`
|
||||
- target **will not be** in the list `deadends`.
|
||||
- `target` and `deadends[i]` consist of digits only.
|
||||
|
||||
## 题目大意
|
||||
|
||||
你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 。每个拨轮可以自由旋转:例如把 '9' 变为 '0','0' 变为 '9' 。每次旋转都只能旋转一个拨轮的一位数字。锁的初始数字为 '0000' ,一个代表四个拨轮的数字的字符串。列表 deadends 包含了一组死亡数字,一旦拨轮的数字和列表里的任何一个元素相同,这个锁将会被永久锁定,无法再被旋转。字符串 target 代表可以解锁的数字,你需要给出解锁需要的最小旋转次数,如果无论如何不能解锁,返回 -1 。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 此题可以转化为从起始点到终点的最短路径。采用广度优先搜索。每次广搜枚举转动一次数字的状态,并且用 visited 记录是否被搜索过,如果没有被搜索过,便加入队列,下一轮继续搜索。如果搜索到了 target,便返回对应的旋转次数。如果搜索完成后,仍没有搜索到 target,说明无法解锁,返回 -1。特殊情况,如果 target 就是初始数字 0000,那么直接返回答案 0。
|
||||
- 在广搜之前,先将 deadends 放入 map 中,搜索中判断是否搜到了 deadends。如果初始数字 0000 出现在 deadends 中,可以直接返回答案 −1。
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
func openLock(deadends []string, target string) int {
|
||||
if target == "0000" {
|
||||
return 0
|
||||
}
|
||||
targetNum, visited := strToInt(target), make([]bool, 10000)
|
||||
visited[0] = true
|
||||
for _, deadend := range deadends {
|
||||
num := strToInt(deadend)
|
||||
if num == 0 {
|
||||
return -1
|
||||
}
|
||||
visited[num] = true
|
||||
}
|
||||
depth, curDepth, nextDepth := 0, []int16{0}, make([]int16, 0)
|
||||
var nextNum int16
|
||||
for len(curDepth) > 0 {
|
||||
nextDepth = nextDepth[0:0]
|
||||
for _, curNum := range curDepth {
|
||||
for incrementer := int16(1000); incrementer > 0; incrementer /= 10 {
|
||||
digit := (curNum / incrementer) % 10
|
||||
if digit == 9 {
|
||||
nextNum = curNum - 9*incrementer
|
||||
} else {
|
||||
nextNum = curNum + incrementer
|
||||
}
|
||||
if nextNum == targetNum {
|
||||
return depth + 1
|
||||
}
|
||||
if !visited[nextNum] {
|
||||
visited[nextNum] = true
|
||||
nextDepth = append(nextDepth, nextNum)
|
||||
}
|
||||
if digit == 0 {
|
||||
nextNum = curNum + 9*incrementer
|
||||
} else {
|
||||
nextNum = curNum - incrementer
|
||||
}
|
||||
if nextNum == targetNum {
|
||||
return depth + 1
|
||||
}
|
||||
if !visited[nextNum] {
|
||||
visited[nextNum] = true
|
||||
nextDepth = append(nextDepth, nextNum)
|
||||
}
|
||||
}
|
||||
}
|
||||
curDepth, nextDepth = nextDepth, curDepth
|
||||
depth++
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func strToInt(str string) int16 {
|
||||
return int16(str[0]-'0')*1000 + int16(str[1]-'0')*100 + int16(str[2]-'0')*10 + int16(str[3]-'0')
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
----------------------------------------------
|
||||
<div style="display: flex;justify-content: space-between;align-items: center;">
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0748.Shortest-Completing-Word/">⬅️上一页</a></p>
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0753.Cracking-the-Safe/">下一页➡️</a></p>
|
||||
</div>
|
@ -94,6 +94,6 @@ func dfsCrackSafe(depth, n, k int, str *[]byte, visit *map[string]bool) bool {
|
||||
|
||||
----------------------------------------------
|
||||
<div style="display: flex;justify-content: space-between;align-items: center;">
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0748.Shortest-Completing-Word/">⬅️上一页</a></p>
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0752.Open-the-Lock/">⬅️上一页</a></p>
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0756.Pyramid-Transition-Matrix/">下一页➡️</a></p>
|
||||
</div>
|
||||
|
@ -199,6 +199,7 @@ weight: 1
|
||||
|0739|Daily Temperatures|[Go]({{< relref "/ChapterFour/0700~0799/0739.Daily-Temperatures.md" >}})|Medium||||65.3%|
|
||||
|0744|Find Smallest Letter Greater Than Target|[Go]({{< relref "/ChapterFour/0700~0799/0744.Find-Smallest-Letter-Greater-Than-Target.md" >}})|Easy||||45.7%|
|
||||
|0746|Min Cost Climbing Stairs|[Go]({{< relref "/ChapterFour/0700~0799/0746.Min-Cost-Climbing-Stairs.md" >}})|Easy| O(n)| O(1)||53.5%|
|
||||
|0752|Open the Lock|[Go]({{< relref "/ChapterFour/0700~0799/0752.Open-the-Lock.md" >}})|Medium||||54.7%|
|
||||
|0766|Toeplitz Matrix|[Go]({{< relref "/ChapterFour/0700~0799/0766.Toeplitz-Matrix.md" >}})|Easy| O(n)| O(1)||65.9%|
|
||||
|0775|Global and Local Inversions|[Go]({{< relref "/ChapterFour/0700~0799/0775.Global-and-Local-Inversions.md" >}})|Medium||||46.0%|
|
||||
|0778|Swim in Rising Water|[Go]({{< relref "/ChapterFour/0700~0799/0778.Swim-in-Rising-Water.md" >}})|Hard||||57.6%|
|
||||
|
@ -39,6 +39,7 @@ weight: 10
|
||||
|0530|Minimum Absolute Difference in BST|[Go]({{< relref "/ChapterFour/0500~0599/0530.Minimum-Absolute-Difference-in-BST.md" >}})|Easy||||55.3%|
|
||||
|0542|01 Matrix|[Go]({{< relref "/ChapterFour/0500~0599/0542.01-Matrix.md" >}})|Medium| O(n)| O(1)||41.6%|
|
||||
|0547|Number of Provinces|[Go]({{< relref "/ChapterFour/0500~0599/0547.Number-of-Provinces.md" >}})|Medium||||61.3%|
|
||||
|0617|Merge Two Binary Trees|[Go]({{< relref "/ChapterFour/0600~0699/0617.Merge-Two-Binary-Trees.md" >}})|Easy||||76.0%|
|
||||
|0623|Add One Row to Tree|[Go]({{< relref "/ChapterFour/0600~0699/0623.Add-One-Row-to-Tree.md" >}})|Medium||||53.2%|
|
||||
|0637|Average of Levels in Binary Tree|[Go]({{< relref "/ChapterFour/0600~0699/0637.Average-of-Levels-in-Binary-Tree.md" >}})|Easy||||66.6%|
|
||||
|0653|Two Sum IV - Input is a BST|[Go]({{< relref "/ChapterFour/0600~0699/0653.Two-Sum-IV-Input-is-a-BST.md" >}})|Easy||||56.6%|
|
||||
@ -49,6 +50,7 @@ weight: 10
|
||||
|0695|Max Area of Island|[Go]({{< relref "/ChapterFour/0600~0699/0695.Max-Area-of-Island.md" >}})|Medium||||66.7%|
|
||||
|0721|Accounts Merge|[Go]({{< relref "/ChapterFour/0700~0799/0721.Accounts-Merge.md" >}})|Medium||||53.0%|
|
||||
|0733|Flood Fill|[Go]({{< relref "/ChapterFour/0700~0799/0733.Flood-Fill.md" >}})|Easy||||56.1%|
|
||||
|0752|Open the Lock|[Go]({{< relref "/ChapterFour/0700~0799/0752.Open-the-Lock.md" >}})|Medium||||54.7%|
|
||||
|0756|Pyramid Transition Matrix|[Go]({{< relref "/ChapterFour/0700~0799/0756.Pyramid-Transition-Matrix.md" >}})|Medium||||55.9%|
|
||||
|0765|Couples Holding Hands|[Go]({{< relref "/ChapterFour/0700~0799/0765.Couples-Holding-Hands.md" >}})|Hard||||55.8%|
|
||||
|0778|Swim in Rising Water|[Go]({{< relref "/ChapterFour/0700~0799/0778.Swim-in-Rising-Water.md" >}})|Hard||||57.6%|
|
||||
|
@ -57,6 +57,7 @@ weight: 9
|
||||
|0563|Binary Tree Tilt|[Go]({{< relref "/ChapterFour/0500~0599/0563.Binary-Tree-Tilt.md" >}})|Easy||||54.0%|
|
||||
|0572|Subtree of Another Tree|[Go]({{< relref "/ChapterFour/0500~0599/0572.Subtree-of-Another-Tree.md" >}})|Easy||||44.7%|
|
||||
|0589|N-ary Tree Preorder Traversal|[Go]({{< relref "/ChapterFour/0500~0599/0589.N-ary-Tree-Preorder-Traversal.md" >}})|Easy||||74.7%|
|
||||
|0617|Merge Two Binary Trees|[Go]({{< relref "/ChapterFour/0600~0699/0617.Merge-Two-Binary-Trees.md" >}})|Easy||||76.0%|
|
||||
|0623|Add One Row to Tree|[Go]({{< relref "/ChapterFour/0600~0699/0623.Add-One-Row-to-Tree.md" >}})|Medium||||53.2%|
|
||||
|0637|Average of Levels in Binary Tree|[Go]({{< relref "/ChapterFour/0600~0699/0637.Average-of-Levels-in-Binary-Tree.md" >}})|Easy||||66.6%|
|
||||
|0653|Two Sum IV - Input is a BST|[Go]({{< relref "/ChapterFour/0600~0699/0653.Two-Sum-IV-Input-is-a-BST.md" >}})|Easy||||56.6%|
|
||||
|
@ -89,6 +89,7 @@ weight: 13
|
||||
|0720|Longest Word in Dictionary|[Go]({{< relref "/ChapterFour/0700~0799/0720.Longest-Word-in-Dictionary.md" >}})|Medium| O(n)| O(n) ||49.7%|
|
||||
|0726|Number of Atoms|[Go]({{< relref "/ChapterFour/0700~0799/0726.Number-of-Atoms.md" >}})|Hard| O(n)| O(n) |❤️|51.1%|
|
||||
|0748|Shortest Completing Word|[Go]({{< relref "/ChapterFour/0700~0799/0748.Shortest-Completing-Word.md" >}})|Easy||||57.9%|
|
||||
|0752|Open the Lock|[Go]({{< relref "/ChapterFour/0700~0799/0752.Open-the-Lock.md" >}})|Medium||||54.7%|
|
||||
|0763|Partition Labels|[Go]({{< relref "/ChapterFour/0700~0799/0763.Partition-Labels.md" >}})|Medium||||78.2%|
|
||||
|0767|Reorganize String|[Go]({{< relref "/ChapterFour/0700~0799/0767.Reorganize-String.md" >}})|Medium||||50.7%|
|
||||
|0771|Jewels and Stones|[Go]({{< relref "/ChapterFour/0700~0799/0771.Jewels-and-Stones.md" >}})|Easy||||87.2%|
|
||||
|
@ -91,6 +91,7 @@ weight: 2
|
||||
|0726|Number of Atoms|[Go]({{< relref "/ChapterFour/0700~0799/0726.Number-of-Atoms.md" >}})|Hard||||51.1%|
|
||||
|0745|Prefix and Suffix Search|[Go]({{< relref "/ChapterFour/0700~0799/0745.Prefix-and-Suffix-Search.md" >}})|Hard||||35.2%|
|
||||
|0748|Shortest Completing Word|[Go]({{< relref "/ChapterFour/0700~0799/0748.Shortest-Completing-Word.md" >}})|Easy||||57.9%|
|
||||
|0752|Open the Lock|[Go]({{< relref "/ChapterFour/0700~0799/0752.Open-the-Lock.md" >}})|Medium||||54.7%|
|
||||
|0763|Partition Labels|[Go]({{< relref "/ChapterFour/0700~0799/0763.Partition-Labels.md" >}})|Medium||||78.2%|
|
||||
|0767|Reorganize String|[Go]({{< relref "/ChapterFour/0700~0799/0767.Reorganize-String.md" >}})|Medium| O(n log n)| O(log n) |❤️|50.7%|
|
||||
|0771|Jewels and Stones|[Go]({{< relref "/ChapterFour/0700~0799/0771.Jewels-and-Stones.md" >}})|Easy||||87.2%|
|
||||
|
@ -55,6 +55,7 @@ weight: 6
|
||||
|0563|Binary Tree Tilt|[Go]({{< relref "/ChapterFour/0500~0599/0563.Binary-Tree-Tilt.md" >}})|Easy||||54.0%|
|
||||
|0572|Subtree of Another Tree|[Go]({{< relref "/ChapterFour/0500~0599/0572.Subtree-of-Another-Tree.md" >}})|Easy||||44.7%|
|
||||
|0589|N-ary Tree Preorder Traversal|[Go]({{< relref "/ChapterFour/0500~0599/0589.N-ary-Tree-Preorder-Traversal.md" >}})|Easy||||74.7%|
|
||||
|0617|Merge Two Binary Trees|[Go]({{< relref "/ChapterFour/0600~0699/0617.Merge-Two-Binary-Trees.md" >}})|Easy||||76.0%|
|
||||
|0623|Add One Row to Tree|[Go]({{< relref "/ChapterFour/0600~0699/0623.Add-One-Row-to-Tree.md" >}})|Medium||||53.2%|
|
||||
|0637|Average of Levels in Binary Tree|[Go]({{< relref "/ChapterFour/0600~0699/0637.Average-of-Levels-in-Binary-Tree.md" >}})|Easy| O(n)| O(n)||66.6%|
|
||||
|0653|Two Sum IV - Input is a BST|[Go]({{< relref "/ChapterFour/0600~0699/0653.Two-Sum-IV-Input-is-a-BST.md" >}})|Easy||||56.6%|
|
||||
|
Reference in New Issue
Block a user