diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README.md b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README.md index 4818d704fc161..700b600874329 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README.md +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README.md @@ -82,14 +82,12 @@ OR 运算节点的值为 True OR False = True 。 我们可以使用递归的方式来求解本题。 -对于当前节点 `root`: +对于当前节点 $\textit{root}$: -- 如果其左右孩子都为空,说明是叶子节点,此时判断其值是否为 $1$,如果是,则返回 `true`,否则返回 `false`。 -- 否则,对其左右孩子分别递归求解,得到其左右孩子的值 $l$ 和 $r$。然后根据当前节点值的不同,分别进行如下操作: - - 如果当前节点值为 $2$,则返回 `l or r`。 - - 如果当前节点值为 $3$,则返回 `l && r`。 +- 如果其左孩子为空,说明当前节点是叶子节点。如果当前节点的值为 $1$,则返回 $\text{true}$,否则返回 $\text{false}$; +- 如果当前节点的值为 $2$,则返回其左孩子和右孩子的递归结果的逻辑或,否则返回其左孩子和右孩子的递归结果的逻辑与。 -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树节点个数。 +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 @@ -104,13 +102,10 @@ OR 运算节点的值为 True OR False = True 。 # self.right = right class Solution: def evaluateTree(self, root: Optional[TreeNode]) -> bool: - def dfs(root): - if root.left is None and root.right is None: - return bool(root.val) - l, r = dfs(root.left), dfs(root.right) - return (l or r) if root.val == 2 else (l and r) - - return dfs(root) + if root.left is None: + return bool(root.val) + op = or_ if root.val == 2 else and_ + return op(self.evaluateTree(root.left), self.evaluateTree(root.right)) ``` #### Java @@ -133,18 +128,13 @@ class Solution: */ class Solution { public boolean evaluateTree(TreeNode root) { - return dfs(root); - } - - private boolean dfs(TreeNode root) { - if (root.left == null && root.right == null) { + if (root.left == null) { return root.val == 1; } - boolean l = dfs(root.left), r = dfs(root.right); if (root.val == 2) { - return l || r; + return evaluateTree(root.left) || evaluateTree(root.right); } - return l && r; + return evaluateTree(root.left) && evaluateTree(root.right); } } ``` @@ -166,14 +156,13 @@ class Solution { class Solution { public: bool evaluateTree(TreeNode* root) { - return dfs(root); - } - - bool dfs(TreeNode* root) { - if (!root->left && !root->right) return root->val; - bool l = dfs(root->left), r = dfs(root->right); - if (root->val == 2) return l || r; - return l && r; + if (!root->left) { + return root->val; + } + if (root->val == 2) { + return evaluateTree(root->left) || evaluateTree(root->right); + } + return evaluateTree(root->left) && evaluateTree(root->right); } }; ``` @@ -190,18 +179,14 @@ public: * } */ func evaluateTree(root *TreeNode) bool { - var dfs func(*TreeNode) bool - dfs = func(root *TreeNode) bool { - if root.Left == nil && root.Right == nil { - return root.Val == 1 - } - l, r := dfs(root.Left), dfs(root.Right) - if root.Val == 2 { - return l || r - } - return l && r + if root.Left == nil { + return root.Val == 1 + } + if root.Val == 2 { + return evaluateTree(root.Left) || evaluateTree(root.Right) + } else { + return evaluateTree(root.Left) && evaluateTree(root.Right) } - return dfs(root) } ``` @@ -224,7 +209,7 @@ func evaluateTree(root *TreeNode) bool { function evaluateTree(root: TreeNode | null): boolean { const { val, left, right } = root; - if (left == null) { + if (left === null) { return val === 1; } if (val === 2) { @@ -257,20 +242,23 @@ function evaluateTree(root: TreeNode | null): boolean { // } use std::cell::RefCell; use std::rc::Rc; -impl Solution { - fn dfs(root: &Option>>) -> bool { - let root = root.as_ref().unwrap().as_ref().borrow(); - if root.left.is_none() { - return root.val == 1; - } - if root.val == 2 { - return Self::dfs(&root.left) || Self::dfs(&root.right); - } - Self::dfs(&root.left) && Self::dfs(&root.right) - } +impl Solution { pub fn evaluate_tree(root: Option>>) -> bool { - Self::dfs(&root) + match root { + Some(node) => { + let node = node.borrow(); + if node.left.is_none() { + return node.val == 1; + } + if node.val == 2 { + return Self::evaluate_tree(node.left.clone()) + || Self::evaluate_tree(node.right.clone()); + } + Self::evaluate_tree(node.left.clone()) && Self::evaluate_tree(node.right.clone()) + } + None => false, + } } } ``` @@ -301,112 +289,4 @@ bool evaluateTree(struct TreeNode* root) { - - -### 方法二 - - - -#### Python3 - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def evaluateTree(self, root: Optional[TreeNode]) -> bool: - if root.left is None: - return bool(root.val) - l = self.evaluateTree(root.left) - r = self.evaluateTree(root.right) - return l or r if root.val == 2 else l and r -``` - -#### Java - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public boolean evaluateTree(TreeNode root) { - if (root.left == null) { - return root.val == 1; - } - boolean l = evaluateTree(root.left); - boolean r = evaluateTree(root.right); - return root.val == 2 ? l || r : l && r; - } -} -``` - -#### C++ - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool evaluateTree(TreeNode* root) { - if (!root->left) { - return root->val; - } - bool l = evaluateTree(root->left); - bool r = evaluateTree(root->right); - return root->val == 2 ? l or r : l and r; - } -}; -``` - -#### Go - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func evaluateTree(root *TreeNode) bool { - if root.Left == nil { - return root.Val == 1 - } - l, r := evaluateTree(root.Left), evaluateTree(root.Right) - if root.Val == 2 { - return l || r - } - return l && r -} -``` - - - - - diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README_EN.md b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README_EN.md index 41d313561cf0d..b137ba6200fe3 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README_EN.md +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README_EN.md @@ -76,7 +76,16 @@ The root node evaluates to True, so we return true. -### Solution 1 +### Solution 1: Recursion + +We can use recursion to solve this problem. + +For the current node $\textit{root}$: + +- If its left child is null, it means the current node is a leaf node. If the value of the current node is $1$, then return $\text{true}$; otherwise, return $\text{false}$; +- If the value of the current node is $2$, then return the logical OR of the recursion results of its left and right children; otherwise, return the logical AND of the recursion results of its left and right children. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. @@ -91,13 +100,10 @@ The root node evaluates to True, so we return true. # self.right = right class Solution: def evaluateTree(self, root: Optional[TreeNode]) -> bool: - def dfs(root): - if root.left is None and root.right is None: - return bool(root.val) - l, r = dfs(root.left), dfs(root.right) - return (l or r) if root.val == 2 else (l and r) - - return dfs(root) + if root.left is None: + return bool(root.val) + op = or_ if root.val == 2 else and_ + return op(self.evaluateTree(root.left), self.evaluateTree(root.right)) ``` #### Java @@ -120,18 +126,13 @@ class Solution: */ class Solution { public boolean evaluateTree(TreeNode root) { - return dfs(root); - } - - private boolean dfs(TreeNode root) { - if (root.left == null && root.right == null) { + if (root.left == null) { return root.val == 1; } - boolean l = dfs(root.left), r = dfs(root.right); if (root.val == 2) { - return l || r; + return evaluateTree(root.left) || evaluateTree(root.right); } - return l && r; + return evaluateTree(root.left) && evaluateTree(root.right); } } ``` @@ -153,14 +154,13 @@ class Solution { class Solution { public: bool evaluateTree(TreeNode* root) { - return dfs(root); - } - - bool dfs(TreeNode* root) { - if (!root->left && !root->right) return root->val; - bool l = dfs(root->left), r = dfs(root->right); - if (root->val == 2) return l || r; - return l && r; + if (!root->left) { + return root->val; + } + if (root->val == 2) { + return evaluateTree(root->left) || evaluateTree(root->right); + } + return evaluateTree(root->left) && evaluateTree(root->right); } }; ``` @@ -177,18 +177,14 @@ public: * } */ func evaluateTree(root *TreeNode) bool { - var dfs func(*TreeNode) bool - dfs = func(root *TreeNode) bool { - if root.Left == nil && root.Right == nil { - return root.Val == 1 - } - l, r := dfs(root.Left), dfs(root.Right) - if root.Val == 2 { - return l || r - } - return l && r + if root.Left == nil { + return root.Val == 1 + } + if root.Val == 2 { + return evaluateTree(root.Left) || evaluateTree(root.Right) + } else { + return evaluateTree(root.Left) && evaluateTree(root.Right) } - return dfs(root) } ``` @@ -211,7 +207,7 @@ func evaluateTree(root *TreeNode) bool { function evaluateTree(root: TreeNode | null): boolean { const { val, left, right } = root; - if (left == null) { + if (left === null) { return val === 1; } if (val === 2) { @@ -244,20 +240,23 @@ function evaluateTree(root: TreeNode | null): boolean { // } use std::cell::RefCell; use std::rc::Rc; -impl Solution { - fn dfs(root: &Option>>) -> bool { - let root = root.as_ref().unwrap().as_ref().borrow(); - if root.left.is_none() { - return root.val == 1; - } - if root.val == 2 { - return Self::dfs(&root.left) || Self::dfs(&root.right); - } - Self::dfs(&root.left) && Self::dfs(&root.right) - } +impl Solution { pub fn evaluate_tree(root: Option>>) -> bool { - Self::dfs(&root) + match root { + Some(node) => { + let node = node.borrow(); + if node.left.is_none() { + return node.val == 1; + } + if node.val == 2 { + return Self::evaluate_tree(node.left.clone()) + || Self::evaluate_tree(node.right.clone()); + } + Self::evaluate_tree(node.left.clone()) && Self::evaluate_tree(node.right.clone()) + } + None => false, + } } } ``` @@ -288,112 +287,4 @@ bool evaluateTree(struct TreeNode* root) { - - -### Solution 2 - - - -#### Python3 - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def evaluateTree(self, root: Optional[TreeNode]) -> bool: - if root.left is None: - return bool(root.val) - l = self.evaluateTree(root.left) - r = self.evaluateTree(root.right) - return l or r if root.val == 2 else l and r -``` - -#### Java - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public boolean evaluateTree(TreeNode root) { - if (root.left == null) { - return root.val == 1; - } - boolean l = evaluateTree(root.left); - boolean r = evaluateTree(root.right); - return root.val == 2 ? l || r : l && r; - } -} -``` - -#### C++ - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool evaluateTree(TreeNode* root) { - if (!root->left) { - return root->val; - } - bool l = evaluateTree(root->left); - bool r = evaluateTree(root->right); - return root->val == 2 ? l or r : l and r; - } -}; -``` - -#### Go - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func evaluateTree(root *TreeNode) bool { - if root.Left == nil { - return root.Val == 1 - } - l, r := evaluateTree(root.Left), evaluateTree(root.Right) - if root.Val == 2 { - return l || r - } - return l && r -} -``` - - - - - diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.cpp b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.cpp index 7904ca8733341..ee40a7299b6a2 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.cpp +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.cpp @@ -12,13 +12,12 @@ class Solution { public: bool evaluateTree(TreeNode* root) { - return dfs(root); - } - - bool dfs(TreeNode* root) { - if (!root->left && !root->right) return root->val; - bool l = dfs(root->left), r = dfs(root->right); - if (root->val == 2) return l || r; - return l && r; + if (!root->left) { + return root->val; + } + if (root->val == 2) { + return evaluateTree(root->left) || evaluateTree(root->right); + } + return evaluateTree(root->left) && evaluateTree(root->right); } }; \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.go b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.go index e9e16ce2f3801..7845d3bce70fe 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.go +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.go @@ -7,16 +7,12 @@ * } */ func evaluateTree(root *TreeNode) bool { - var dfs func(*TreeNode) bool - dfs = func(root *TreeNode) bool { - if root.Left == nil && root.Right == nil { - return root.Val == 1 - } - l, r := dfs(root.Left), dfs(root.Right) - if root.Val == 2 { - return l || r - } - return l && r + if root.Left == nil { + return root.Val == 1 + } + if root.Val == 2 { + return evaluateTree(root.Left) || evaluateTree(root.Right) + } else { + return evaluateTree(root.Left) && evaluateTree(root.Right) } - return dfs(root) } \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.java b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.java index f39e3671d451b..5e021a9667551 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.java +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.java @@ -15,17 +15,12 @@ */ class Solution { public boolean evaluateTree(TreeNode root) { - return dfs(root); - } - - private boolean dfs(TreeNode root) { - if (root.left == null && root.right == null) { + if (root.left == null) { return root.val == 1; } - boolean l = dfs(root.left), r = dfs(root.right); if (root.val == 2) { - return l || r; + return evaluateTree(root.left) || evaluateTree(root.right); } - return l && r; + return evaluateTree(root.left) && evaluateTree(root.right); } } \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.py b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.py index 75b51b5a7a707..396c09e4f865f 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.py +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.py @@ -6,10 +6,7 @@ # self.right = right class Solution: def evaluateTree(self, root: Optional[TreeNode]) -> bool: - def dfs(root): - if root.left is None and root.right is None: - return bool(root.val) - l, r = dfs(root.left), dfs(root.right) - return (l or r) if root.val == 2 else (l and r) - - return dfs(root) + if root.left is None: + return bool(root.val) + op = or_ if root.val == 2 else and_ + return op(self.evaluateTree(root.left), self.evaluateTree(root.right)) diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.rs b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.rs index f613c59be70f1..91c0191f95a24 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.rs +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.rs @@ -18,19 +18,22 @@ // } use std::cell::RefCell; use std::rc::Rc; -impl Solution { - fn dfs(root: &Option>>) -> bool { - let root = root.as_ref().unwrap().as_ref().borrow(); - if root.left.is_none() { - return root.val == 1; - } - if root.val == 2 { - return Self::dfs(&root.left) || Self::dfs(&root.right); - } - Self::dfs(&root.left) && Self::dfs(&root.right) - } +impl Solution { pub fn evaluate_tree(root: Option>>) -> bool { - Self::dfs(&root) + match root { + Some(node) => { + let node = node.borrow(); + if node.left.is_none() { + return node.val == 1; + } + if node.val == 2 { + return Self::evaluate_tree(node.left.clone()) + || Self::evaluate_tree(node.right.clone()); + } + Self::evaluate_tree(node.left.clone()) && Self::evaluate_tree(node.right.clone()) + } + None => false, + } } } diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.ts b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.ts index e7038328a0d35..9bce84aba9869 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.ts +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.ts @@ -14,7 +14,7 @@ function evaluateTree(root: TreeNode | null): boolean { const { val, left, right } = root; - if (left == null) { + if (left === null) { return val === 1; } if (val === 2) { diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.cpp b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.cpp deleted file mode 100644 index fe76cf937ecbc..0000000000000 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool evaluateTree(TreeNode* root) { - if (!root->left) { - return root->val; - } - bool l = evaluateTree(root->left); - bool r = evaluateTree(root->right); - return root->val == 2 ? l or r : l and r; - } -}; \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.go b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.go deleted file mode 100644 index 3acf50ef352a3..0000000000000 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.go +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func evaluateTree(root *TreeNode) bool { - if root.Left == nil { - return root.Val == 1 - } - l, r := evaluateTree(root.Left), evaluateTree(root.Right) - if root.Val == 2 { - return l || r - } - return l && r -} \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.java b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.java deleted file mode 100644 index ce00b11f767d8..0000000000000 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public boolean evaluateTree(TreeNode root) { - if (root.left == null) { - return root.val == 1; - } - boolean l = evaluateTree(root.left); - boolean r = evaluateTree(root.right); - return root.val == 2 ? l || r : l && r; - } -} \ No newline at end of file diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.py b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.py deleted file mode 100644 index 3fdfcb7659bb1..0000000000000 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution2.py +++ /dev/null @@ -1,13 +0,0 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def evaluateTree(self, root: Optional[TreeNode]) -> bool: - if root.left is None: - return bool(root.val) - l = self.evaluateTree(root.left) - r = self.evaluateTree(root.right) - return l or r if root.val == 2 else l and r diff --git a/solution/2900-2999/2974.Minimum Number Game/README.md b/solution/2900-2999/2974.Minimum Number Game/README.md index be7563a32ac95..d219d417acf24 100644 --- a/solution/2900-2999/2974.Minimum Number Game/README.md +++ b/solution/2900-2999/2974.Minimum Number Game/README.md @@ -68,9 +68,9 @@ tags: ### 方法一:模拟 + 优先队列(小根堆) -我们可以将数组 $nums$ 中的元素依次放入一个小根堆中,每次从小根堆中取出两个元素 $a$ 和 $b$,然后依次将 $b$ 和 $a$ 放入答案数组中,直到小根堆为空。 +我们可以将数组 $\textit{nums}$ 中的元素依次放入一个小根堆中,每次从小根堆中取出两个元素 $a$ 和 $b$,然后依次将 $b$ 和 $a$ 放入答案数组中,直到小根堆为空。 -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $\textit{nums}$ 的长度。 @@ -217,9 +217,9 @@ impl Solution { ### 方法二:排序 + 交换 -我们可以将数组 $nums$ 排序,然后依次将相邻的两个元素交换位置,即可得到答案数组。 +我们可以将数组 $\textit{nums}$ 排序,然后遍历数组,每次交换相邻的两个元素,直到遍历结束,返回交换后的数组。 -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 $nums$ 的长度。 +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 $\textit{nums}$ 的长度。 diff --git a/solution/2900-2999/2974.Minimum Number Game/README_EN.md b/solution/2900-2999/2974.Minimum Number Game/README_EN.md index ea00e12d69ec4..8a530d375804e 100644 --- a/solution/2900-2999/2974.Minimum Number Game/README_EN.md +++ b/solution/2900-2999/2974.Minimum Number Game/README_EN.md @@ -66,9 +66,9 @@ At the begining of round two, nums = [5,4]. Now, first Alice removes 4 and then ### Solution 1: Simulation + Priority Queue (Min Heap) -We can put the elements in the array $nums$ into a min heap one by one, and each time take out two elements $a$ and $b$ from the min heap, then put $b$ and $a$ into the answer array in turn, until the min heap is empty. +We can put the elements of the array $\textit{nums}$ into a min heap one by one. Each time, we take out two elements $a$ and $b$ from the min heap, and then sequentially put $b$ and $a$ into the answer array until the min heap is empty. -Time complexity is $O(n \times \log n)$, and space complexity is $O(n)$. Where $n$ is the length of the array $nums$. +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\textit{nums}$. @@ -215,9 +215,9 @@ impl Solution { ### Solution 2: Sorting + Swapping -We can sort the array $nums$, and then swap the positions of every two adjacent elements in sequence to get the answer array. +We can sort the array $\textit{nums}$, and then iterate through the array, swapping adjacent elements each time until the iteration is complete, and return the swapped array. -The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Where $n$ is the length of the array $nums$. +The time complexity is $O(n \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $\textit{nums}$. diff --git a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README.md b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README.md index 8a286c9d07e8f..1dc9cc9e6dd26 100644 --- a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README.md +++ b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README.md @@ -72,9 +72,9 @@ tags: ### 方法一:枚举 -我们可以枚举 $hFences$ 中的任意两条水平栅栏 $a$ 和 $b$,计算 $a$ 和 $b$ 之间的距离 $d$,记录在哈希表 $hs$ 中,然后枚举 $vFences$ 中的任意两条垂直栅栏 $c$ 和 $d$,计算 $c$ 和 $d$ 之间的距离 $d$,记录在哈希表 $vs$ 中,最后遍历哈希表 $hs$,如果 $hs$ 中的某个距离 $d$ 在哈希表 $vs$ 中也存在,那么说明存在一个正方形田地,其边长为 $d$,面积为 $d^2$,我们只需要取最大的 $d$,求 $d^2 \bmod 10^9 + 7$ 即可。 +我们可以枚举 $\textit{hFences}$ 中的任意两条水平栅栏 $a$ 和 $b$,计算 $a$ 和 $b$ 之间的距离 $d$,记录在哈希表 $hs$ 中,然后枚举 $\textit{vFences}$ 中的任意两条垂直栅栏 $c$ 和 $d$,计算 $c$ 和 $d$ 之间的距离 $d$,记录在哈希表 $vs$ 中,最后遍历哈希表 $hs$,如果 $hs$ 中的某个距离 $d$ 在哈希表 $vs$ 中也存在,那么说明存在一个正方形田地,其边长为 $d$,面积为 $d^2$,我们只需要取最大的 $d$,求 $d^2 \bmod 10^9 + 7$ 即可。 -时间复杂度 $O(h^2 + v^2)$,空间复杂度 $O(h^2 + v^2)$。其中 $h$ 和 $v$ 分别是 $hFences$ 和 $vFences$ 的长度。 +时间复杂度 $O(h^2 + v^2)$,空间复杂度 $O(h^2 + v^2)$。其中 $h$ 和 $v$ 分别是 $\textit{hFences}$ 和 $\textit{vFences}$ 的长度。 diff --git a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README_EN.md b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README_EN.md index b64005eacc8c5..546ebd38f4a8a 100644 --- a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README_EN.md +++ b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README_EN.md @@ -70,9 +70,9 @@ tags: ### Solution 1: Enumeration -We can enumerate any two horizontal fences $a$ and $b$ in $hFences$, calculate the distance $d$ between $a$ and $b$, and record it in the hash table $hs$. Then, we enumerate any two vertical fences $c$ and $d$ in $vFences$, calculate the distance $d$ between $c$ and $d$, and record it in the hash table $vs$. Finally, we traverse the hash table $hs$. If a distance $d$ in $hs$ also exists in the hash table $vs$, it means that there exists a square field with a side length of $d$ and an area of $d^2$. We just need to take the largest $d$ and calculate $d^2 \bmod 10^9 + 7$. +We can enumerate any two horizontal fences $a$ and $b$ in $\textit{hFences}$, calculate the distance $d$ between $a$ and $b$, and record it in the hash table $hs$. Then, we enumerate any two vertical fences $c$ and $d$ in $\textit{vFences}$, calculate the distance $d$ between $c$ and $d$, and record it in the hash table $vs$. Finally, we traverse the hash table $hs$. If a certain distance $d$ in $hs$ also exists in the hash table $vs$, it indicates that there exists a square field with a side length of $d$, and the area is $d^2$. We just need to take the largest $d$ and calculate $d^2 \bmod 10^9 + 7$. -The time complexity is $O(h^2 + v^2)$, and the space complexity is $O(h^2 + v^2)$. Where $h$ and $v$ are the lengths of $hFences$ and $vFences$ respectively. +The time complexity is $O(h^2 + v^2)$, and the space complexity is $O(h^2 + v^2)$. Here, $h$ and $v$ are the lengths of $\textit{hFences}$ and $\textit{vFences}$, respectively. diff --git a/solution/2900-2999/2976.Minimum Cost to Convert String I/README.md b/solution/2900-2999/2976.Minimum Cost to Convert String I/README.md index c581c9b46204b..89e7133abb6a4 100644 --- a/solution/2900-2999/2976.Minimum Cost to Convert String I/README.md +++ b/solution/2900-2999/2976.Minimum Cost to Convert String I/README.md @@ -90,7 +90,7 @@ tags: 根据题目描述,我们可以将每个字母看作一个节点,每对字母的转换成本看作一条有向边。那么我们先初始化一个 $26 \times 26$ 的二维数组 $g$,其中 $g[i][j]$ 表示字母 $i$ 转换成字母 $j$ 的最小成本。初始时 $g[i][j] = \infty$,如果 $i = j$,那么 $g[i][j] = 0$。 -然后我们遍历数组 $original$、$changed$ 和 $cost$,对于每个下标 $i$,我们将 $original[i]$ 转换成 $changed[i]$ 的成本 $cost[i]$ 更新到 $g[original[i]][changed[i]]$ 中,取最小值。 +然后我们遍历数组 $original$, $changed$ 和 $cost$,对于每个下标 $i$,我们将 $original[i]$ 转换成 $changed[i]$ 的成本 $cost[i]$ 更新到 $g[original[i]][changed[i]]$ 中,取最小值。 接下来,我们使用 Floyd 算法计算出 $g$ 中任意两个节点之间的最小成本。最后,我们遍历字符串 $source$ 和 $target$,如果 $source[i] \neq target[i]$,并且 $g[source[i]][target[i]] \geq \infty$,那么说明无法完成转换,返回 $-1$。否则,我们将 $g[source[i]][target[i]]$ 累加到答案中。 diff --git a/solution/3000-3099/3011.Find if Array Can Be Sorted/README.md b/solution/3000-3099/3011.Find if Array Can Be Sorted/README.md index bb59981a6f7bb..713e7117307af 100644 --- a/solution/3000-3099/3011.Find if Array Can Be Sorted/README.md +++ b/solution/3000-3099/3011.Find if Array Can Be Sorted/README.md @@ -76,9 +76,9 @@ tags: ### 方法一:双指针 -我们可以使用双指针,将数组 $nums$ 分成若干个子数组,每个子数组中的元素的二进制表示中 $1$ 的个数相同。对于每个子数组,我们只需要关注它的最大值和最小值,如果最小值比上一个子数组的最大值小,那么就无法通过交换使得数组有序。 +我们可以使用双指针,将数组 $\textit{nums}$ 分成若干个子数组,每个子数组中的元素的二进制表示中 $1$ 的个数相同。对于每个子数组,我们只需要关注它的最大值和最小值,如果最小值比上一个子数组的最大值小,那么就无法通过交换使得数组有序。 -时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 +时间复杂度 $O(n)$,其中 $n$ 是数组 $\textit{nums}$ 的长度。空间复杂度 $O(1)$。 @@ -87,11 +87,11 @@ tags: ```python class Solution: def canSortArray(self, nums: List[int]) -> bool: - pre_mx = -inf + pre_mx = 0 i, n = 0, len(nums) while i < n: - j = i + 1 cnt = nums[i].bit_count() + j = i + 1 mi = mx = nums[i] while j < n and nums[j].bit_count() == cnt: mi = min(mi, nums[j]) @@ -109,11 +109,11 @@ class Solution: ```java class Solution { public boolean canSortArray(int[] nums) { - int preMx = -300; + int preMx = 0; int i = 0, n = nums.length; while (i < n) { - int j = i + 1; int cnt = Integer.bitCount(nums[i]); + int j = i + 1; int mi = nums[i], mx = nums[i]; while (j < n && Integer.bitCount(nums[j]) == cnt) { mi = Math.min(mi, nums[j]); @@ -137,11 +137,11 @@ class Solution { class Solution { public: bool canSortArray(vector& nums) { - int preMx = -300; + int preMx = 0; int i = 0, n = nums.size(); while (i < n) { - int j = i + 1; int cnt = __builtin_popcount(nums[i]); + int j = i + 1; int mi = nums[i], mx = nums[i]; while (j < n && __builtin_popcount(nums[j]) == cnt) { mi = min(mi, nums[j]); @@ -163,11 +163,11 @@ public: ```go func canSortArray(nums []int) bool { - preMx := -300 + preMx := 0 i, n := 0, len(nums) for i < n { - j := i + 1 cnt := bits.OnesCount(uint(nums[i])) + j := i + 1 mi, mx := nums[i], nums[i] for j < n && bits.OnesCount(uint(nums[j])) == cnt { mi = min(mi, nums[j]) @@ -188,11 +188,11 @@ func canSortArray(nums []int) bool { ```ts function canSortArray(nums: number[]): boolean { - let preMx = -300; + let preMx = 0; const n = nums.length; for (let i = 0; i < n; ) { - let j = i + 1; const cnt = bitCount(nums[i]); + let j = i + 1; let [mi, mx] = [nums[i], nums[i]]; while (j < n && bitCount(nums[j]) === cnt) { mi = Math.min(mi, nums[j]); diff --git a/solution/3000-3099/3011.Find if Array Can Be Sorted/README_EN.md b/solution/3000-3099/3011.Find if Array Can Be Sorted/README_EN.md index 517f9a2b7df35..37a51c81306da 100644 --- a/solution/3000-3099/3011.Find if Array Can Be Sorted/README_EN.md +++ b/solution/3000-3099/3011.Find if Array Can Be Sorted/README_EN.md @@ -74,9 +74,9 @@ Note that there may be other sequences of operations which also sort the array. ### Solution 1: Two Pointers -We can use two pointers to divide the array $nums$ into several subarrays, each with the same number of 1s in the binary representation of its elements. For each subarray, we only need to focus on its maximum and minimum values. If the minimum value is smaller than the maximum value of the previous subarray, then it is impossible to make the array sorted by swapping. +We can use two pointers to divide the array $\textit{nums}$ into several subarrays, each subarray containing elements with the same number of $1$s in their binary representation. For each subarray, we only need to focus on its maximum and minimum values. If the minimum value is less than the maximum value of the previous subarray, then it is impossible to make the array ordered by swapping. -The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. +The time complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$. The space complexity is $O(1)$. @@ -85,11 +85,11 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The ```python class Solution: def canSortArray(self, nums: List[int]) -> bool: - pre_mx = -inf + pre_mx = 0 i, n = 0, len(nums) while i < n: - j = i + 1 cnt = nums[i].bit_count() + j = i + 1 mi = mx = nums[i] while j < n and nums[j].bit_count() == cnt: mi = min(mi, nums[j]) @@ -107,11 +107,11 @@ class Solution: ```java class Solution { public boolean canSortArray(int[] nums) { - int preMx = -300; + int preMx = 0; int i = 0, n = nums.length; while (i < n) { - int j = i + 1; int cnt = Integer.bitCount(nums[i]); + int j = i + 1; int mi = nums[i], mx = nums[i]; while (j < n && Integer.bitCount(nums[j]) == cnt) { mi = Math.min(mi, nums[j]); @@ -135,11 +135,11 @@ class Solution { class Solution { public: bool canSortArray(vector& nums) { - int preMx = -300; + int preMx = 0; int i = 0, n = nums.size(); while (i < n) { - int j = i + 1; int cnt = __builtin_popcount(nums[i]); + int j = i + 1; int mi = nums[i], mx = nums[i]; while (j < n && __builtin_popcount(nums[j]) == cnt) { mi = min(mi, nums[j]); @@ -161,11 +161,11 @@ public: ```go func canSortArray(nums []int) bool { - preMx := -300 + preMx := 0 i, n := 0, len(nums) for i < n { - j := i + 1 cnt := bits.OnesCount(uint(nums[i])) + j := i + 1 mi, mx := nums[i], nums[i] for j < n && bits.OnesCount(uint(nums[j])) == cnt { mi = min(mi, nums[j]) @@ -186,11 +186,11 @@ func canSortArray(nums []int) bool { ```ts function canSortArray(nums: number[]): boolean { - let preMx = -300; + let preMx = 0; const n = nums.length; for (let i = 0; i < n; ) { - let j = i + 1; const cnt = bitCount(nums[i]); + let j = i + 1; let [mi, mx] = [nums[i], nums[i]]; while (j < n && bitCount(nums[j]) === cnt) { mi = Math.min(mi, nums[j]); diff --git a/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.cpp b/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.cpp index 536ede1e831e7..119f956f22b59 100644 --- a/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.cpp +++ b/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.cpp @@ -1,11 +1,11 @@ class Solution { public: bool canSortArray(vector& nums) { - int preMx = -300; + int preMx = 0; int i = 0, n = nums.size(); while (i < n) { - int j = i + 1; int cnt = __builtin_popcount(nums[i]); + int j = i + 1; int mi = nums[i], mx = nums[i]; while (j < n && __builtin_popcount(nums[j]) == cnt) { mi = min(mi, nums[j]); diff --git a/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.go b/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.go index d1377609ffe8d..cdc367e1bb241 100644 --- a/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.go +++ b/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.go @@ -1,9 +1,9 @@ func canSortArray(nums []int) bool { - preMx := -300 + preMx := 0 i, n := 0, len(nums) for i < n { - j := i + 1 cnt := bits.OnesCount(uint(nums[i])) + j := i + 1 mi, mx := nums[i], nums[i] for j < n && bits.OnesCount(uint(nums[j])) == cnt { mi = min(mi, nums[j]) diff --git a/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.java b/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.java index ace5dfc7934af..47b6064353b18 100644 --- a/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.java +++ b/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.java @@ -1,10 +1,10 @@ class Solution { public boolean canSortArray(int[] nums) { - int preMx = -300; + int preMx = 0; int i = 0, n = nums.length; while (i < n) { - int j = i + 1; int cnt = Integer.bitCount(nums[i]); + int j = i + 1; int mi = nums[i], mx = nums[i]; while (j < n && Integer.bitCount(nums[j]) == cnt) { mi = Math.min(mi, nums[j]); diff --git a/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.py b/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.py index 51191418e1026..8c790d0ea2688 100644 --- a/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.py +++ b/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.py @@ -1,10 +1,10 @@ class Solution: def canSortArray(self, nums: List[int]) -> bool: - pre_mx = -inf + pre_mx = 0 i, n = 0, len(nums) while i < n: - j = i + 1 cnt = nums[i].bit_count() + j = i + 1 mi = mx = nums[i] while j < n and nums[j].bit_count() == cnt: mi = min(mi, nums[j]) diff --git a/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.ts b/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.ts index c02c50778d879..b7ad1abee66c1 100644 --- a/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.ts +++ b/solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.ts @@ -1,9 +1,9 @@ function canSortArray(nums: number[]): boolean { - let preMx = -300; + let preMx = 0; const n = nums.length; for (let i = 0; i < n; ) { - let j = i + 1; const cnt = bitCount(nums[i]); + let j = i + 1; let [mi, mx] = [nums[i], nums[i]]; while (j < n && bitCount(nums[j]) === cnt) { mi = Math.min(mi, nums[j]);