提交 85debd25 编写于 作者: ToTensor's avatar ToTensor

修复习题数量

上级 51d0acd2
{ {
"node_id": "dailycode-3ff87eb146d34897b954ad46df29bcb6", "node_id": "dailycode-d335de511b684c29bfea723f6d33a0e4",
"keywords": [], "keywords": [],
"children": [], "children": [],
"keywords_must": [], "keywords_must": [],
......
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "930f3279f4384794846104506be93185",
"author": "csdn.net",
"keywords": "树,二叉搜索树,数组,分治,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 将有序数组转换为二叉搜索树
<p>给你一个整数数组 <code>nums</code> ,其中元素已经按 <strong>升序</strong> 排列,请你将其转换为一棵 <strong>高度平衡</strong> 二叉搜索树。</p>
<p><strong>高度平衡 </strong>二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg" style="width: 302px; height: 222px;" />
<pre>
<strong>输入:</strong>nums = [-10,-3,0,5,9]
<strong>输出:</strong>[0,-3,9,-10,null,5]
<strong>解释:</strong>[0,-10,5,null,-3,null,9] 也将被视为正确答案:
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/18/btree2.jpg" style="width: 302px; height: 222px;" />
</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/18/btree.jpg" style="width: 342px; height: 142px;" />
<pre>
<strong>输入:</strong>nums = [1,3]
<strong>输出:</strong>[3,1]
<strong>解释:</strong>[1,3] 和 [3,1] 都是高度平衡二叉搜索树。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
<li><code>nums</code><strong>严格递增</strong> 顺序排列</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *sortedArrayToBST(vector<int> &nums)
{
return dfs(nums, 0, nums.size() - 1);
}
TreeNode *dfs(vector<int> &nums, int left, int right)
{
if (left > right)
return NULL;
int mid = (left + right) / 2;
TreeNode *t = new TreeNode(nums[mid]);
t->left = dfs(nums, left, mid - 1);
t->right = dfs(nums, mid + 1, right);
return t;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{ {
"node_id": "dailycode-97e15a0f1bdf4c899838b347b1983dc5", "node_id": "dailycode-a83634532b824c769445b10d596917f6",
"keywords": [], "keywords": [],
"children": [], "children": [],
"keywords_must": [], "keywords_must": [],
......
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "15135e7668e043e7bb577426de5369b2",
"author": "csdn.net",
"keywords": "树,深度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 平衡二叉树
<p>给定一个二叉树,判断它是否是高度平衡的二叉树。</p>
<p>本题中,一棵高度平衡二叉树定义为:</p>
<blockquote>
<p>一个二叉树<em>每个节点 </em>的左右两个子树的高度差的绝对值不超过 1 。</p>
</blockquote>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg" style="width: 342px; height: 221px;" />
<pre>
<strong>输入:</strong>root = [3,9,20,null,null,15,7]
<strong>输出:</strong>true
</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg" style="width: 452px; height: 301px;" />
<pre>
<strong>输入:</strong>root = [1,2,2,3,3,null,null,4,4]
<strong>输出:</strong>false
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>root = []
<strong>输出:</strong>true
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中的节点数在范围 <code>[0, 5000]</code></li>
<li><code>-10<sup>4</sup> <= Node.val <= 10<sup>4</sup></code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int depth(TreeNode *root)
{
if (root == NULL)
return 0;
int left = depth(root->left);
int right = depth(root->right);
return max(left, right) + 1;
}
bool isBalanced(TreeNode *root)
{
if (root == NULL)
return true;
if (abs(depth(root->left) - depth(root->right)) > 1)
return false;
else
return isBalanced(root->left) && isBalanced(root->right);
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{ {
"node_id": "dailycode-451470417dde4c61a764f65ac405267d", "node_id": "dailycode-c8023cfe856c4678aa96956db32b5470",
"keywords": [], "keywords": [],
"children": [], "children": [],
"keywords_must": [], "keywords_must": [],
......
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "c0299f55bbee4aceb2c6c6ffc245db84",
"author": "csdn.net",
"keywords": "树,深度优先搜索,广度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 二叉树的最小深度
<p>给定一个二叉树,找出其最小深度。</p>
<p>最小深度是从根节点到最近叶子节点的最短路径上的节点数量。</p>
<p><strong>说明:</strong>叶子节点是指没有子节点的节点。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg" style="width: 432px; height: 302px;" />
<pre>
<strong>输入:</strong>root = [3,9,20,null,null,15,7]
<strong>输出:</strong>2
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>root = [2,null,3,null,4,null,5,null,6]
<strong>输出:</strong>5
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点数的范围在 <code>[0, 10<sup>5</sup>]</code></li>
<li><code>-1000 <= Node.val <= 1000</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int minDepth(TreeNode *root)
{
if (!root)
return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
return (left && right) ? 1 + min(left, right) : 1 + left + right;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{ {
"node_id": "dailycode-a38c1abb007e45c38ff0968c13fd28ac", "node_id": "dailycode-fb518fd9317c4e229cee01ac248ce804",
"keywords": [], "keywords": [],
"children": [], "children": [],
"keywords_must": [], "keywords_must": [],
......
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "3e479d9fb28042b89d7b21dbd2029d20",
"author": "csdn.net",
"keywords": "树,深度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 路径总和
<p>给你二叉树的根节点 <code>root</code> 和一个表示目标和的整数 <code>targetSum</code> ,判断该树中是否存在 <strong>根节点到叶子节点</strong> 的路径,这条路径上所有节点值相加等于目标和 <code>targetSum</code></p>
<p><strong>叶子节点</strong> 是指没有子节点的节点。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg" style="width: 500px; height: 356px;" />
<pre>
<strong>输入:</strong>root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
<strong>输出:</strong>true
</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" />
<pre>
<strong>输入:</strong>root = [1,2,3], targetSum = 5
<strong>输出:</strong>false
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>root = [1,2], targetSum = 0
<strong>输出:</strong>false
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点的数目在范围 <code>[0, 5000]</code></li>
<li><code>-1000 <= Node.val <= 1000</code></li>
<li><code>-1000 <= targetSum <= 1000</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
bool hasPathSum(TreeNode *root, int sum)
{
bool flag = false;
backTrack(root, sum, flag);
return flag;
}
void backTrack(TreeNode *root, int sum, bool &flag)
{
if (!root)
{
return;
}
if (!root->left && !root->right)
{
sum -= root->val;
if (sum == 0)
{
flag = true;
}
sum += root->val;
return;
}
sum -= root->val;
backTrack(root->left, sum, flag);
backTrack(root->right, sum, flag);
sum += root->val;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-14e9caac11dc4882b6acbc4e7a4ff49d",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "5f4adb247b224514bbb0d937491de500",
"author": "csdn.net",
"keywords": "数组,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 杨辉三角
<p>给定一个非负整数 <em><code>numRows</code></em>生成「杨辉三角」的前 <em><code>numRows</code> </em>行。</p>
<p><small>在「杨辉三角」中,每个数是它左上方和右上方的数的和。</small></p>
<p><img alt="" src="https://pic.leetcode-cn.com/1626927345-DZmfxB-PascalTriangleAnimated2.gif" /></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> numRows = 5
<strong>输出:</strong> [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> numRows = 1
<strong>输出:</strong> [[1]]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= numRows <= 30</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<vector<int>> generate(int numRows)
{
if (numRows <= 0)
{
return {};
}
if (numRows == 1)
{
return {{1}};
}
if (numRows == 2)
{
return {{1}, {1, 1}};
}
vector<vector<int>> res = {{1}, {1, 1}};
vector<int> arr;
int row = 1;
while (row < numRows - 1)
{
arr.push_back(1);
for (int i = 0; i < res[row].size() - 1; i++)
{
int temp = 0;
temp = res[row][i] + res[row][i + 1];
arr.push_back(temp);
}
arr.push_back(1);
res.push_back(arr);
arr.clear();
row++;
}
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-163199273b89450f9621cbdf0da4f01b",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "bbfbabf7e95e4c9b884d37ee321dfe98",
"author": "csdn.net",
"keywords": "数组,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 杨辉三角 II
<p>给定一个非负索引 <code>rowIndex</code>,返回「杨辉三角」的第 <code>rowIndex</code><em> </em>行。</p>
<p><small>在「杨辉三角」中,每个数是它左上方和右上方的数的和。</small></p>
<p><img alt="" src="https://pic.leetcode-cn.com/1626927345-DZmfxB-PascalTriangleAnimated2.gif" /></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> rowIndex = 3
<strong>输出:</strong> [1,3,3,1]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> rowIndex = 0
<strong>输出:</strong> [1]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong> rowIndex = 1
<strong>输出:</strong> [1,1]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 <= rowIndex <= 33</code></li>
</ul>
<p> </p>
<p><strong>进阶:</strong></p>
<p>你可以优化你的算法到 <code><em>O</em>(<i>rowIndex</i>)</code> 空间复杂度吗?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> getRow(int rowIndex)
{
vector<int> res(rowIndex + 1, 1);
for (int i = 0; i < rowIndex + 1; ++i)
{
for (int j = i - 1; j > 0; --j)
{
res[j] = res[j] + res[j - 1];
}
}
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-26c2393a211f4f74aae41a5c5b6f1194",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "9e7555f4e1674542b7f3a4de8eb56e17",
"author": "csdn.net",
"keywords": "数组,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 买卖股票的最佳时机
<p>给定一个数组 <code>prices</code> ,它的第 <code>i</code> 个元素 <code>prices[i]</code> 表示一支给定股票第 <code>i</code> 天的价格。</p>
<p>你只能选择 <strong>某一天</strong> 买入这只股票,并选择在 <strong>未来的某一个不同的日子</strong> 卖出该股票。设计一个算法来计算你所能获取的最大利润。</p>
<p>返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 <code>0</code></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>[7,1,5,3,6,4]
<strong>输出:</strong>5
<strong>解释:</strong>在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>prices = [7,6,4,3,1]
<strong>输出:</strong>0
<strong>解释:</strong>在这种情况下, 没有交易完成, 所以最大利润为 0。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= prices.length <= 10<sup>5</sup></code></li>
<li><code>0 <= prices[i] <= 10<sup>4</sup></code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
int profit = INT_MIN;
int buy = INT_MAX;
for (int i = 0; i < prices.size(); i++)
{
int temp = prices[i] - buy;
if (temp > profit)
{
profit = temp;
}
if (temp < 0)
{
buy = prices[i];
}
}
return (profit > 0) ? profit : 0;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-0a92b1231f904f52a9bc75a9e427173d",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "b91fef5ce7a146aabae6bd7bb2a99add",
"author": "csdn.net",
"keywords": "贪心,数组,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 买卖股票的最佳时机 II
<p>给定一个数组 <code>prices</code> ,其中 <code>prices[i]</code> 是一支给定股票第 <code>i</code> 天的价格。</p>
<p>设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。</p>
<p><strong>注意:</strong>你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> prices = [7,1,5,3,6,4]
<strong>输出:</strong> 7
<strong>解释:</strong> 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
  随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> prices = [1,2,3,4,5]
<strong>输出:</strong> 4
<strong>解释:</strong> 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
  注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong> prices = [7,6,4,3,1]
<strong>输出:</strong> 0
<strong>解释:</strong> 在这种情况下, 没有交易完成, 所以最大利润为 0。</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= prices.length <= 3 * 10<sup>4</sup></code></li>
<li><code>0 <= prices[i] <= 10<sup>4</sup></code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
if (prices.empty())
return 0;
int cnt = 0;
for (int i = 0; i < prices.size() - 1; ++i)
{
if (prices[i] < prices[i + 1])
cnt += prices[i + 1] - prices[i];
}
return cnt;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-e74a8997c29746c4800782a33e2c7640",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "b38a53d95a234b7db1ab99300bb7acc3",
"author": "csdn.net",
"keywords": "双指针,字符串",
"notebook_enable": true
}
\ No newline at end of file
# 验证回文串
<p>给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。</p>
<p><strong>说明:</strong>本题中,我们将空字符串定义为有效的回文串。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> "A man, a plan, a canal: Panama"
<strong>输出:</strong> true
<strong>解释:</strong>"amanaplanacanalpanama" 是回文串
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> "race a car"
<strong>输出:</strong> false
<strong>解释:</strong>"raceacar" 不是回文串
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= s.length <= 2 * 10<sup>5</sup></code></li>
<li>字符串 <code>s</code> 由 ASCII 字符组成</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isPalindrome(string s)
{
int left = 0, right;
if ((right = s.size()) == 0)
{
return true;
}
while (left < right)
{
while (left < right && !isalnum(s[left]))
{
left++;
}
while (left < right && !isalnum(s[right]))
{
right--;
}
if (left < right)
{
if (tolower(s[left]) != tolower(s[right]))
{
return false;
}
}
left++;
right--;
}
return true;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-219df52f601244238513e7de7e2003ed",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "d2339dc4d7f441a8b34f9e4b08c5c6f4",
"author": "csdn.net",
"keywords": "位运算,数组",
"notebook_enable": true
}
\ No newline at end of file
# 只出现一次的数字
<p>给定一个<strong>非空</strong>整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。</p>
<p><strong>说明:</strong></p>
<p>你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> [2,2,1]
<strong>输出:</strong> 1
</pre>
<p><strong>示例&nbsp;2:</strong></p>
<pre><strong>输入:</strong> [4,1,2,1,2]
<strong>输出:</strong> 4</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int singleNumber(vector<int> &nums)
{
int res = 0;
for (int i = 0; i < nums.size(); i++)
{
res ^= nums[i];
}
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-55f3974a87a84f75bb2893cb290fde96",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "3294f78b036849119b70d3638940a8d6",
"author": "csdn.net",
"keywords": "哈希表,链表,双指针",
"notebook_enable": true
}
\ No newline at end of file
# 环形链表
<p>给定一个链表,判断链表中是否有环。</p>
<p>如果链表中有某个节点,可以通过连续跟踪 <code>next</code> 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 <code>pos</code> 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 <code>pos</code><code>-1</code>,则在该链表中没有环。<strong>注意:<code>pos</code> 不作为参数进行传递</strong>,仅仅是为了标识链表的实际情况。</p>
<p>如果链表中存在环,则返回 <code>true</code> 。 否则,返回 <code>false</code></p>
<p>&nbsp;</p>
<p><strong>进阶:</strong></p>
<p>你能用 <em>O(1)</em>(即,常量)内存解决此问题吗?</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist.png" style="height: 97px; width: 300px;"></p>
<pre><strong>输入:</strong>head = [3,2,0,-4], pos = 1
<strong>输出:</strong>true
<strong>解释:</strong>链表中有一个环,其尾部连接到第二个节点。
</pre>
<p><strong>示例&nbsp;2:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test2.png" style="height: 74px; width: 141px;"></p>
<pre><strong>输入:</strong>head = [1,2], pos = 0
<strong>输出:</strong>true
<strong>解释:</strong>链表中有一个环,其尾部连接到第一个节点。
</pre>
<p><strong>示例 3:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test3.png" style="height: 45px; width: 45px;"></p>
<pre><strong>输入:</strong>head = [1], pos = -1
<strong>输出:</strong>false
<strong>解释:</strong>链表中没有环。
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li>链表中节点的数目范围是 <code>[0, 10<sup>4</sup>]</code></li>
<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
<li><code>pos</code><code>-1</code> 或者链表中的一个 <strong>有效索引</strong></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
bool hasCycle(ListNode *head)
{
ListNode *faster = head;
ListNode *slower = head;
if (head == NULL)
return false;
while (faster != NULL && faster->next != NULL)
{
faster = faster->next->next;
slower = slower->next;
if (faster == slower)
return true;
}
return false;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-1651f0143f344641870e403e0fecd732",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "d171b0899a7d4fa9b685c5aa42d83779",
"author": "csdn.net",
"keywords": "栈,树,深度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 二叉树的前序遍历
<p>给你二叉树的根节点 <code>root</code> ,返回它节点值的 <strong>前序</strong><em> </em>遍历。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" style="width: 202px; height: 324px;" />
<pre>
<strong>输入:</strong>root = [1,null,2,3]
<strong>输出:</strong>[1,2,3]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>root = []
<strong>输出:</strong>[]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>root = [1]
<strong>输出:</strong>[1]
</pre>
<p><strong>示例 4:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/inorder_5.jpg" style="width: 202px; height: 202px;" />
<pre>
<strong>输入:</strong>root = [1,2]
<strong>输出:</strong>[1,2]
</pre>
<p><strong>示例 5:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/inorder_4.jpg" style="width: 202px; height: 202px;" />
<pre>
<strong>输入:</strong>root = [1,null,2]
<strong>输出:</strong>[1,2]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点数目在范围 <code>[0, 100]</code></li>
<li><code>-100 <= Node.val <= 100</code></li>
</ul>
<p> </p>
<p><strong>进阶:</strong>递归算法很简单,你可以通过迭代算法完成吗?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
private:
void rec(TreeNode *root, vector<int> &ret)
{
if (root != NULL)
{
rec(root->right, ret);
rec(root->left, ret);
ret.push_back(root->val);
}
}
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> ret;
rec(root, ret);
return ret;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-2d3f0bbed569420195f24c6ab63fd904",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "01609a836c924ff6beb0ecc2881f99ef",
"author": "csdn.net",
"keywords": "栈,树,深度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 二叉树的后序遍历
<p>给定一个二叉树,返回它的 <em>后序&nbsp;</em>遍历。</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong> [1,null,2,3]
1
\
2
/
3
<strong>输出:</strong> [3,2,1]</pre>
<p><strong>进阶:</strong>&nbsp;递归算法很简单,你可以通过迭代算法完成吗?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> postorderTraversal(TreeNode *root)
{
dfs(root);
return temp;
}
void dfs(TreeNode *root)
{
if (root == NULL)
return;
dfs(root->left);
dfs(root->right);
temp.push_back(root->val);
}
vector<int> temp;
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-709d66df256d4328a79b6e8cb3c2d392",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{ {
"type": "code_options", "type": "code_options",
"source": "solution.md", "source": "solution.md",
"exercise_id": "423a11a1e52a42bfaf4c5664486742f3", "exercise_id": "27b8c45d6f09499fac37e611062195b0",
"author": "csdn.net", "author": "csdn.net",
"keywords": "数据库" "keywords": "栈,设计",
"notebook_enable": true
} }
\ No newline at end of file
# 最小栈
<p>设计一个支持 <code>push</code><code>pop</code><code>top</code> 操作,并能在常数时间内检索到最小元素的栈。</p>
<ul>
<li><code>push(x)</code> &mdash;&mdash; 将元素 x 推入栈中。</li>
<li><code>pop()</code>&nbsp;&mdash;&mdash; 删除栈顶的元素。</li>
<li><code>top()</code>&nbsp;&mdash;&mdash; 获取栈顶元素。</li>
<li><code>getMin()</code> &mdash;&mdash; 检索栈中的最小元素。</li>
</ul>
<p>&nbsp;</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong>
[&quot;MinStack&quot;,&quot;push&quot;,&quot;push&quot;,&quot;push&quot;,&quot;getMin&quot;,&quot;pop&quot;,&quot;top&quot;,&quot;getMin&quot;]
[[],[-2],[0],[-3],[],[],[],[]]
<strong>输出:</strong>
[null,null,null,null,-3,null,0,-2]
<strong>解释:</strong>
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --&gt; 返回 -3.
minStack.pop();
minStack.top(); --&gt; 返回 0.
minStack.getMin(); --&gt; 返回 -2.
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>pop</code><code>top</code><code>getMin</code> 操作总是在 <strong>非空栈</strong> 上调用。</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class MinStack
{
public:
stack<int> s;
stack<int> min;
/** initialize your data structure here. */
MinStack()
{
}
void push(int x)
{
s.push(x);
if (min.empty() || x <= min.top())
{
min.push(x);
}
}
void pop()
{
if (s.top() == min.top())
min.pop();
s.pop();
}
int top()
{
return s.top();
}
int getMin()
{
return min.top();
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-2bc75d75d57b4807a2edf0eb18eb5c8c",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "2450b377ecaa4e0a9dd4f7d682a4af21",
"author": "csdn.net",
"keywords": "哈希表,链表,双指针",
"notebook_enable": true
}
\ No newline at end of file
# 相交链表
<p>给你两个单链表的头节点 <code>headA</code><code>headB</code> ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 <code>null</code></p>
<p>图示两个链表在节点 <code>c1</code> 开始相交<strong></strong></p>
<p><a href="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/14/160_statement.png" target="_blank"><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/14/160_statement.png" style="height: 130px; width: 400px;" /></a></p>
<p>题目数据 <strong>保证</strong> 整个链式结构中不存在环。</p>
<p><strong>注意</strong>,函数返回结果后,链表必须 <strong>保持其原始结构</strong></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<p><a href="https://assets.leetcode.com/uploads/2018/12/13/160_example_1.png" target="_blank"><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/14/160_example_1.png" style="height: 130px; width: 400px;" /></a></p>
<pre>
<strong>输入:</strong>intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
<strong>输出:</strong>Intersected at '8'
<strong>解释:</strong>相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。
在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
</pre>
<p><strong>示例 2:</strong></p>
<p><a href="https://assets.leetcode.com/uploads/2018/12/13/160_example_2.png" target="_blank"><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/14/160_example_2.png" style="height: 136px; width: 350px;" /></a></p>
<pre>
<strong>输入:</strong>intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
<strong>输出:</strong>Intersected at '2'
<strong>解释:</strong>相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。
在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
</pre>
<p><strong>示例 3:</strong></p>
<p><a href="https://assets.leetcode.com/uploads/2018/12/13/160_example_3.png" target="_blank"><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/14/160_example_3.png" style="height: 126px; width: 200px;" /></a></p>
<pre>
<strong>输入:</strong>intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
<strong>输出:</strong>null
<strong>解释:</strong>从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。
由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
这两个链表不相交,因此返回 null 。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>listA</code> 中节点数目为 <code>m</code></li>
<li><code>listB</code> 中节点数目为 <code>n</code></li>
<li><code>0 <= m, n <= 3 * 10<sup>4</sup></code></li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
<li><code>0 <= skipA <= m</code></li>
<li><code>0 <= skipB <= n</code></li>
<li>如果 <code>listA</code><code>listB</code> 没有交点,<code>intersectVal</code><code>0</code></li>
<li>如果 <code>listA</code><code>listB</code> 有交点,<code>intersectVal == listA[skipA + 1] == listB[skipB + 1]</code></li>
</ul>
<p> </p>
<p><strong>进阶:</strong>你能否设计一个时间复杂度 <code>O(n)</code> 、仅用 <code>O(1)</code> 内存的解决方案?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
if (!headA || !headB)
{
return NULL;
}
ListNode *cur1 = headA;
ListNode *cur2 = headB;
while (cur1 != cur2)
{
cur1 = cur1 ? cur1->next : headB;
cur2 = cur2 ? cur2->next : headA;
}
return cur1;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-68803d4d5df0420eabfef657c0df9560",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "e15e9d7a6a034088b2384779c02275af",
"author": "csdn.net",
"keywords": "数组,双指针,二分查找",
"notebook_enable": true
}
\ No newline at end of file
# 两数之和 II
<p>给定一个已按照<strong><em> </em>非递减顺序排列&nbsp; </strong>的整数数组&nbsp;<code>numbers</code> ,请你从数组中找出两个数满足相加之和等于目标数&nbsp;<code>target</code></p>
<p>函数应该以长度为 <code>2</code> 的整数数组的形式返回这两个数的下标值<em></em><code>numbers</code> 的下标 <strong>从 1 开始计数</strong> ,所以答案数组应当满足 <code>1 &lt;= answer[0] &lt; answer[1] &lt;= numbers.length</code></p>
<p>你可以假设每个输入 <strong>只对应唯一的答案</strong> ,而且你 <strong>不可以</strong> 重复使用相同的元素。</p>
&nbsp;
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>numbers = [2,7,11,15], target = 9
<strong>输出:</strong>[1,2]
<strong>解释:</strong>2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>numbers = [2,3,4], target = 6
<strong>输出:</strong>[1,3]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>numbers = [-1,0], target = -1
<strong>输出:</strong>[1,2]
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>2 &lt;= numbers.length &lt;= 3 * 10<sup>4</sup></code></li>
<li><code>-1000 &lt;= numbers[i] &lt;= 1000</code></li>
<li><code>numbers</code><strong>非递减顺序</strong> 排列</li>
<li><code>-1000 &lt;= target &lt;= 1000</code></li>
<li><strong>仅存在一个有效答案</strong></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
int low = 0, high = numbers.size() - 1;
while (low < high)
{
int sum = numbers[low] + numbers[high];
if (sum == target)
{
return {low + 1, high + 1};
}
if (sum < target)
{
++low;
}
else
{
--high;
}
}
return {-1, -1};
}
}
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-8337bc578dd54305bcbcf6445d06af30",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "787031c1bf0b4f81b66999b3f4b42146",
"author": "csdn.net",
"keywords": "数学,字符串",
"notebook_enable": true
}
\ No newline at end of file
# Excel表列名称
<p>给你一个整数 <code>columnNumber</code> ,返回它在 Excel 表中相对应的列名称。</p>
<p>例如:</p>
<pre>
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
</pre>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>columnNumber = 1
<strong>输出:</strong>"A"
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>columnNumber = 28
<strong>输出:</strong>"AB"
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>columnNumber = 701
<strong>输出:</strong>"ZY"
</pre>
<p><strong>示例 4:</strong></p>
<pre>
<strong>输入:</strong>columnNumber = 2147483647
<strong>输出:</strong>"FXSHRXW"
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= columnNumber <= 2<sup>31</sup> - 1</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
string convertToTitle(int n)
{
string res;
while (n)
{
int temp = n % 26;
n /= 26;
if (temp)
res.push_back('A' + temp - 1);
else
{
res.push_back('Z');
n--;
}
}
reverse(res.begin(), res.end());
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-962b9124033e41d49aa3481c7dfab494",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "3063239bef37448aaddac259ac4b4649",
"author": "csdn.net",
"keywords": "数组,哈希表,分治,计数,排序",
"notebook_enable": true
}
\ No newline at end of file
# 多数元素
<p>给定一个大小为 <em>n </em>的数组,找到其中的多数元素。多数元素是指在数组中出现次数 <strong>大于</strong> <code>⌊ n/2 ⌋</code> 的元素。</p>
<p>你可以假设数组是非空的,并且给定的数组总是存在多数元素。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>[3,2,3]
<strong>输出:</strong>3</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>[2,2,1,1,1,2,2]
<strong>输出:</strong>2
</pre>
<p> </p>
<p><strong>进阶:</strong></p>
<ul>
<li>尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int majorityElement(vector<int> &nums)
{
unordered_map<int, int> counts;
int majority = 0, cnt = 0;
for (int num : nums)
{
++counts[num];
if (counts[num] > cnt)
{
majority = num;
cnt = counts[num];
}
}
return majority;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-bc50522c68bf48fd97e6f613722f66fa",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "ba1063921dbe41418dee9ce903777741",
"author": "csdn.net",
"keywords": "数学,字符串",
"notebook_enable": true
}
\ No newline at end of file
# Excel表列序号
<p>给你一个字符串&nbsp;<code>columnTitle</code> ,表示 Excel 表格中的列名称。返回该列名称对应的列序号。</p>
<p>&nbsp;</p>
<p>例如,</p>
<pre>
A -&gt; 1
B -&gt; 2
C -&gt; 3
...
Z -&gt; 26
AA -&gt; 27
AB -&gt; 28
...
</pre>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> columnTitle = "A"
<strong>输出:</strong> 1
</pre>
<p><strong>示例&nbsp;2:</strong></p>
<pre>
<strong>输入: </strong>columnTitle = "AB"
<strong>输出:</strong> 28
</pre>
<p><strong>示例&nbsp;3:</strong></p>
<pre>
<strong>输入: </strong>columnTitle = "ZY"
<strong>输出:</strong> 701</pre>
<p><strong>示例 4:</strong></p>
<pre>
<strong>输入: </strong>columnTitle = "FXSHRXW"
<strong>输出: </strong>2147483647
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= columnTitle.length &lt;= 7</code></li>
<li><code>columnTitle</code> 仅由大写英文组成</li>
<li><code>columnTitle</code> 在范围 <code>["A", "FXSHRXW"]</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int titleToNumber(string s)
{
long num = 0;
for (int i = 0; i < s.size(); i++)
{
num = (num * 26) + (s[i] - 64);
}
return num;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-345aecfe47a24f5aa0a5a616aa82d801",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{ {
"type": "code_options", "type": "code_options",
"source": "solution.md", "source": "solution.md",
"exercise_id": "99f8cccc1b934f6e92b94a26f0ccc34c", "exercise_id": "090510ef86b14cb08933325e85f553dd",
"author": "csdn.net", "author": "csdn.net",
"keywords": "双指针,字符串" "keywords": "数学",
"notebook_enable": true
} }
\ No newline at end of file
# 阶乘后的零
<p>给定一个整数 <code>n</code> ,返回 <code>n!</code> 结果中尾随零的数量。</p>
<p>提示&nbsp;<code>n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1</code></p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>n = 3
<strong>输出:</strong>0
<strong>解释:</strong>3! = 6 ,不含尾随 0
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>n = 5
<strong>输出:</strong>1
<strong>解释:</strong>5! = 120 ,有一个尾随 0
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>n = 0
<strong>输出:</strong>0
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 &lt;= n &lt;= 10<sup>4</sup></code></li>
</ul>
<p>&nbsp;</p>
<p><b>进阶:</b>你可以设计并实现对数时间复杂度的算法来解决此问题吗?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int trailingZeroes(int n)
{
int numOfZeros = 0;
while (n > 0)
{
numOfZeros += numOf5(n);
n--;
}
return numOfZeros;
}
int numOf5(int num)
{
int count = 0;
while ((num > 1) && (num % 5 == 0))
{
count++;
num /= 5;
}
return count;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-524ced2fd5dd476bbfa3314db321e961",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "1bf7c916bc354627b654aff938342c0f",
"author": "csdn.net",
"keywords": "位运算,分治",
"notebook_enable": true
}
\ No newline at end of file
# 颠倒二进制位
<p>颠倒给定的 32 位无符号整数的二进制位。</p>
<p><strong>提示:</strong></p>
<ul>
<li>请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。</li>
<li>在 Java 中,编译器使用<a href="https://baike.baidu.com/item/二进制补码/5295284" target="_blank">二进制补码</a>记法来表示有符号整数。因此,在 <strong>示例 2</strong>&nbsp;中,输入表示有符号整数 <code>-3</code>,输出表示有符号整数 <code>-1073741825</code></li>
</ul>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>n = 00000010100101000001111010011100
<strong>输出:</strong>964176192 (00111001011110000010100101000000)
<strong>解释:</strong>输入的二进制串 <strong>00000010100101000001111010011100 </strong>表示无符号整数<strong> 43261596</strong><strong>
</strong> 因此返回 964176192,其二进制表示形式为 <strong>00111001011110000010100101000000</strong></pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>n = 11111111111111111111111111111101
<strong>输出:</strong>3221225471 (10111111111111111111111111111111)
<strong>解释:</strong>输入的二进制串 <strong>11111111111111111111111111111101</strong> 表示无符号整数 4294967293,
&nbsp; 因此返回 3221225471 其二进制表示形式为 <strong>10111111111111111111111111111111 。</strong></pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li>输入是一个长度为 <code>32</code> 的二进制字符串</li>
</ul>
<p>&nbsp;</p>
<p><strong>进阶</strong>: 如果多次调用这个函数,你将如何优化你的算法?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
uint32_t reverseBits(uint32_t n)
{
uint32_t res = 0;
for (int i = 0; i < 32; i++)
{
res <<= 1;
res |= n & 1;
n >>= 1;
}
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-e7e53eb27fac437d9d1a3dbdc258d5bf",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{ {
"type": "code_options", "type": "code_options",
"source": "solution.md", "source": "solution.md",
"exercise_id": "12b418be49d0440d80d23d1498d77aea", "exercise_id": "e9ed6c10cc8046fdb9c2f303c9827372",
"author": "csdn.net", "author": "csdn.net",
"keywords": "哈希表,字符串,滑动窗口" "keywords": "位运算",
"notebook_enable": true
} }
\ No newline at end of file
# 位1的个数
<p>编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为<a href="https://baike.baidu.com/item/%E6%B1%89%E6%98%8E%E9%87%8D%E9%87%8F" target="_blank">汉明重量</a>)。</p>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。</li>
<li>在 Java 中,编译器使用<a href="https://baike.baidu.com/item/二进制补码/5295284" target="_blank">二进制补码</a>记法来表示有符号整数。因此,在上面的 <strong>示例 3</strong> 中,输入表示有符号整数 <code>-3</code></li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>00000000000000000000000000001011
<strong>输出:</strong>3
<strong>解释:</strong>输入的二进制串 <code><strong>00000000000000000000000000001011</strong> 中,共有三位为 '1'。</code>
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>00000000000000000000000010000000
<strong>输出:</strong>1
<strong>解释:</strong>输入的二进制串 <strong>00000000000000000000000010000000</strong> 中,共有一位为 '1'。
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>11111111111111111111111111111101
<strong>输出:</strong>31
<strong>解释:</strong>输入的二进制串 <strong>11111111111111111111111111111101</strong> 中,共有 31 位为 '1'。</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>输入必须是长度为 <code>32</code><strong>二进制串</strong></li>
</ul>
<ul>
</ul>
<p> </p>
<p><strong>进阶</strong></p>
<ul>
<li>如果多次调用这个函数,你将如何优化你的算法?</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int hammingWeight(uint32_t n)
{
int count = 0;
uint32_t res = 1;
for (int i = 0; i < 32; i++)
{
if (res & n)
{
count++;
}
n >>= 1;
}
return count;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-15f39c759f9b4aa99bb75b00bcf0580c",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "dd2a5b9e9ed849f5b905fbbd20b230ea",
"author": "csdn.net",
"keywords": "哈希表,数学,双指针",
"notebook_enable": true
}
\ No newline at end of file
# 快乐数
<p>编写一个算法来判断一个数 <code>n</code> 是不是快乐数。</p>
<p>「快乐数」定义为:</p>
<ul>
<li>对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。</li>
<li>然后重复这个过程直到这个数变为 1,也可能是 <strong>无限循环</strong> 但始终变不到 1。</li>
<li>如果 <strong>可以变为</strong>  1,那么这个数就是快乐数。</li>
</ul>
<p>如果 <code>n</code> 是快乐数就返回 <code>true</code> ;不是,则返回 <code>false</code></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>19
<strong>输出:</strong>true
<strong>解释:
</strong>1<sup>2</sup> + 9<sup>2</sup> = 82
8<sup>2</sup> + 2<sup>2</sup> = 68
6<sup>2</sup> + 8<sup>2</sup> = 100
1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>n = 2
<strong>输出:</strong>false
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>31</sup> - 1</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isHappy(int n)
{
set<int> s;
while (n != 1)
{
int t = 0;
while (n)
{
t += (n % 10) * (n % 10);
n /= 10;
}
int size = s.size();
s.insert(t);
if (size == s.size())
return false;
n = t;
}
return true;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-ae3f500a3fd948b59a5433ed9e3abee5",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "764671b466ae41c7918438e006b78d38",
"author": "csdn.net",
"keywords": "递归,链表",
"notebook_enable": true
}
\ No newline at end of file
# 移除链表元素
给你一个链表的头节点 <code>head</code> 和一个整数 <code>val</code> ,请你删除链表中所有满足 <code>Node.val == val</code> 的节点,并返回 <strong>新的头节点</strong>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/06/removelinked-list.jpg" style="width: 500px; height: 142px;" />
<pre>
<strong>输入:</strong>head = [1,2,6,3,4,5,6], val = 6
<strong>输出:</strong>[1,2,3,4,5]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>head = [], val = 1
<strong>输出:</strong>[]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>head = [7,7,7,7], val = 7
<strong>输出:</strong>[]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>列表中的节点数目在范围 <code>[0, 10<sup>4</sup>]</code></li>
<li><code>1 <= Node.val <= 50</code></li>
<li><code>0 <= val <= 50</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *removeElements(ListNode *head, int val)
{
ListNode *dumynode = new ListNode(0);
dumynode->next = head;
ListNode *fast = dumynode->next;
ListNode *slow = dumynode;
while (fast != NULL)
{
if (fast->val == val)
{
slow->next = slow->next->next;
}
else
{
slow = slow->next;
}
fast = fast->next;
}
ListNode *ret = dumynode->next;
delete dumynode;
return ret;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-7259fff1111e46ffa29f196ba542ba00",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "27936a1703b94c82bcc9f781c9194893",
"author": "csdn.net",
"keywords": "数组,数学,枚举,数论",
"notebook_enable": true
}
\ No newline at end of file
# 计数质数
<p>统计所有小于非负整数&nbsp;<em><code>n</code>&nbsp;</em>的质数的数量。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong>n = 10
<strong>输出:</strong>4
<strong>解释:</strong>小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong>n = 0
<strong>输出:</strong>0
</pre>
<p><strong>示例 3:</strong></p>
<pre><strong>输入:</strong>n = 1
<strong>输出</strong>:0
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 &lt;= n &lt;= 5 * 10<sup>6</sup></code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int countPrimes(int n)
{
vector<bool> primesMap(n, true);
int count = 0;
for (int i = 2; i < n; i++)
{
if (primesMap[i])
{
count++;
for (int j = 2 * i; j < n; j += i)
{
primesMap[j] = false;
}
}
}
return count;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-0e10486e4e8640adae0e951917a26845",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "a240d4ffd705492787e87d9cf88bcab4",
"author": "csdn.net",
"keywords": "哈希表,字符串",
"notebook_enable": true
}
\ No newline at end of file
# 同构字符串
<p>给定两个字符串 <em><strong></strong></em>和 <strong><em>t</em></strong>,判断它们是否是同构的。</p>
<p>如果 <em><strong></strong></em>中的字符可以按某种映射关系替换得到 <strong><em></em></strong>,那么这两个字符串是同构的。</p>
<p>每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong><strong><em>s</em></strong> = <code>"egg", </code><strong><em>t = </em></strong><code>"add"</code>
<strong>输出:</strong>true
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong><strong><em>s</em></strong> = <code>"foo", </code><strong><em>t = </em></strong><code>"bar"</code>
<strong>输出:</strong>false</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong><strong><em>s</em></strong> = <code>"paper", </code><strong><em>t = </em></strong><code>"title"</code>
<strong>输出:</strong>true</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>可以假设 <em><strong></strong></em><strong><em>t </em></strong>长度相同。</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isIsomorphic(string s, string t)
{
vector<int> m(128, -1);
for (int i = 0; i < s.size(); ++i)
{
if (m[s[i]] != -1)
{
if (m[s[i]] != t[i])
return false;
}
else
{
for (auto v : m)
{
if (v == t[i])
return false;
}
m[s[i]] = t[i];
}
}
return true;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-88db4509fe484d61a6dcf07943003cb1",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "d26956dec2844546a98f1ea107b00a65",
"author": "csdn.net",
"keywords": "递归,链表",
"notebook_enable": true
}
\ No newline at end of file
# 反转链表
给你单链表的头节点 <code>head</code> ,请你反转链表,并返回反转后的链表。
<div class="original__bRMd">
<div>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg" style="width: 542px; height: 222px;" />
<pre>
<strong>输入:</strong>head = [1,2,3,4,5]
<strong>输出:</strong>[5,4,3,2,1]
</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg" style="width: 182px; height: 222px;" />
<pre>
<strong>输入:</strong>head = [1,2]
<strong>输出:</strong>[2,1]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>head = []
<strong>输出:</strong>[]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>链表中节点的数目范围是 <code>[0, 5000]</code></li>
<li><code>-5000 <= Node.val <= 5000</code></li>
</ul>
<p> </p>
<p><strong>进阶:</strong>链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?</p>
</div>
</div>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *reverseList(ListNode *head)
{
if (head == NULL)
return NULL;
ListNode *node = NULL;
ListNode *temp = head;
ListNode *temp1 = head;
while (true)
{
if (temp->next == NULL)
{
temp1 = temp;
temp1->next = node;
break;
}
temp1 = temp;
temp = temp->next;
temp1->next = node;
node = temp1;
}
return temp1;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-510c86fa67d842068f7c3f018e8f89d9",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "c1b8804fd7a14cef8cd5f20e0f4ff762",
"author": "csdn.net",
"keywords": "数组,哈希表,排序",
"notebook_enable": true
}
\ No newline at end of file
# 存在重复元素
<p>给定一个整数数组,判断是否存在重复元素。</p>
<p>如果存在一值在数组中出现至少两次,函数返回 <code>true</code> 。如果数组中每个元素都不相同,则返回 <code>false</code></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> [1,2,3,1]
<strong>输出:</strong> true</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入: </strong>[1,2,3,4]
<strong>输出:</strong> false</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入: </strong>[1,1,1,3,3,4,3,2,4,2]
<strong>输出:</strong> true</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool containsDuplicate(vector<int> &nums)
{
if (nums.empty())
{
return false;
}
sort(nums.begin(), nums.begin() + nums.size());
for (int i = 0; i < nums.size() - 1; i++)
{
if (nums[i] == nums[i + 1])
{
return true;
}
}
return false;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-6326da4a969f49dc810d995343223f5e",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "243066531cd64f568c3a8386611c0089",
"author": "csdn.net",
"keywords": "数组,哈希表,滑动窗口",
"notebook_enable": true
}
\ No newline at end of file
# 存在重复元素 II
<p>给定一个整数数组和一个整数&nbsp;<em>k</em>,判断数组中是否存在两个不同的索引<em>&nbsp;i</em>&nbsp;<em>&nbsp;j</em>,使得&nbsp;<strong>nums [i] = nums [j]</strong>,并且 <em>i</em><em>j</em>&nbsp;的差的 <strong>绝对值</strong> 至多为 <em>k</em></p>
<p>&nbsp;</p>
<p><strong>示例&nbsp;1:</strong></p>
<pre><strong>输入:</strong> nums = [1,2,3,1], k<em> </em>= 3
<strong>输出:</strong> true</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入: </strong>nums = [1,0,1,1], k<em> </em>=<em> </em>1
<strong>输出:</strong> true</pre>
<p><strong>示例 3:</strong></p>
<pre><strong>输入: </strong>nums = [1,2,3,1,2,3], k<em> </em>=<em> </em>2
<strong>输出:</strong> false</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool containsNearbyDuplicate(vector<int> &nums, int k)
{
int n = nums.size(), idx = 0;
unordered_map<int, int> nmap;
for (int i = 0; i < n; ++i)
{
auto iter = nmap.find(nums[i]);
if (iter != nmap.end())
{
if (i - iter->second <= k)
return true;
else
iter->second = i;
}
else
nmap[nums[i]] = i;
}
return false;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-50e1cb8edc1d4dc19b4d95ab248cbe36",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "86948c5e7a8a44ce9a4c9acc737a3770",
"author": "csdn.net",
"keywords": "栈,设计,队列",
"notebook_enable": true
}
\ No newline at end of file
# 用队列实现栈
<p>请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(<code>push</code><code>top</code><code>pop</code><code>empty</code>)。</p>
<p>实现 <code>MyStack</code> 类:</p>
<ul>
<li><code>void push(int x)</code> 将元素 x 压入栈顶。</li>
<li><code>int pop()</code> 移除并返回栈顶元素。</li>
<li><code>int top()</code> 返回栈顶元素。</li>
<li><code>boolean empty()</code> 如果栈是空的,返回 <code>true</code> ;否则,返回 <code>false</code></li>
</ul>
<p> </p>
<p><strong>注意:</strong></p>
<ul>
<li>你只能使用队列的基本操作 —— 也就是 <code>push to back</code><code>peek/pop from front</code><code>size</code> 和 <code>is empty</code> 这些操作。</li>
<li>你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。</li>
</ul>
<p> </p>
<p><strong>示例:</strong></p>
<pre>
<strong>输入:</strong>
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
<strong>输出:</strong>
[null, null, null, 2, 2, false]
<strong>解释:</strong>
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= x <= 9</code></li>
<li>最多调用<code>100</code><code>push</code><code>pop</code><code>top</code><code>empty</code></li>
<li>每次调用 <code>pop</code><code>top</code> 都保证栈不为空</li>
</ul>
<p> </p>
<p><strong>进阶:</strong>你能否实现每种操作的均摊时间复杂度为 <code>O(1)</code> 的栈?换句话说,执行 <code>n</code> 个操作的总时间复杂度 <code>O(n)</code> ,尽管其中某个操作可能需要比其他操作更长的时间。你可以使用两个以上的队列。</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class MyStack
{
public:
MyStack()
{
}
void push(int x)
{
std::queue<int> temp_queue;
temp_queue.push(x);
while (!_data.empty())
{
temp_queue.push(_data.front());
_data.pop();
}
while (!temp_queue.empty())
{
_data.push(temp_queue.front());
temp_queue.pop();
}
}
int pop()
{
int x = _data.front();
_data.pop();
return x;
}
int top()
{
return _data.front();
}
bool empty()
{
return _data.empty();
}
private:
std::queue<int> _data;
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-e1a1c4598bdb483a8b73a902222956df",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "68c7ad63c6ac42af89a763d04013e0f2",
"author": "csdn.net",
"keywords": "树,深度优先搜索,广度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 翻转二叉树
<p>翻转一棵二叉树。</p>
<p><strong>示例:</strong></p>
<p>输入:</p>
<pre> 4
/ \
2 7
/ \ / \
1 3 6 9</pre>
<p>输出:</p>
<pre> 4
/ \
7 2
/ \ / \
9 6 3 1</pre>
<p><strong>备注:</strong><br>
这个问题是受到 <a href="https://twitter.com/mxcl" target="_blank">Max Howell </a><a href="https://twitter.com/mxcl/status/608682016205344768" target="_blank">原问题</a> 启发的 :</p>
<blockquote>谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。</blockquote>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *invertTree(TreeNode *root)
{
if (!root)
{
return root;
}
TreeNode *temp = root->left;
root->left = invertTree(root->right);
root->right = invertTree(temp);
return root;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-3ee24b6deba740379e077abdc180342f",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{ {
"type": "code_options", "type": "code_options",
"source": "solution.md", "source": "solution.md",
"exercise_id": "d61ff566c89342b888c5df90a0fa5007", "exercise_id": "79ea6f8b6f134986bb083e68baeb4266",
"author": "csdn.net", "author": "csdn.net",
"keywords": "树,深度优先搜索,二叉树" "keywords": "数组",
"notebook_enable": true
} }
\ No newline at end of file
# 汇总区间
<p>给定一个无重复元素的有序整数数组 <code>nums</code></p>
<p>返回 <strong>恰好覆盖数组中所有数字</strong><strong>最小有序</strong> 区间范围列表。也就是说,<code>nums</code> 的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个范围但不属于 <code>nums</code> 的数字 <code>x</code></p>
<p>列表中的每个区间范围 <code>[a,b]</code> 应该按如下格式输出:</p>
<ul>
<li><code>"a->b"</code> ,如果 <code>a != b</code></li>
<li><code>"a"</code> ,如果 <code>a == b</code></li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>nums = [0,1,2,4,5,7]
<strong>输出:</strong>["0->2","4->5","7"]
<strong>解释:</strong>区间范围是:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [0,2,3,4,6,8,9]
<strong>输出:</strong>["0","2->4","6","8->9"]
<strong>解释:</strong>区间范围是:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>nums = []
<strong>输出:</strong>[]
</pre>
<p><strong>示例 4:</strong></p>
<pre>
<strong>输入:</strong>nums = [-1]
<strong>输出:</strong>["-1"]
</pre>
<p><strong>示例 5:</strong></p>
<pre>
<strong>输入:</strong>nums = [0]
<strong>输出:</strong>["0"]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 <= nums.length <= 20</code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>nums</code> 中的所有值都 <strong>互不相同</strong></li>
<li><code>nums</code> 按升序排列</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<string> summaryRanges(vector<int> &nums)
{
int n = nums.size();
vector<string> ans;
int i = 0;
while (i < n)
{
int j = i;
while (j + 1 < n && nums[j + 1] == nums[j] + 1)
j++;
if (i == j)
ans.push_back(to_string(nums[i]));
else
ans.push_back(to_string(nums[i]) + "->" + to_string(nums[j]));
i = j + 1;
}
return ans;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-73795c2480d4451cbba108521a80078c",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "4ca1d7d6fdc3440390e82ed46d4bed70",
"author": "csdn.net",
"keywords": "位运算,递归,数学",
"notebook_enable": true
}
\ No newline at end of file
# 2 的幂
<p>给你一个整数 <code>n</code>,请你判断该整数是否是 2 的幂次方。如果是,返回 <code>true</code> ;否则,返回 <code>false</code></p>
<p>如果存在一个整数 <code>x</code> 使得 <code>n == 2<sup>x</sup></code> ,则认为 <code>n</code> 是 2 的幂次方。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>n = 1
<strong>输出:</strong>true
<strong>解释:</strong>2<sup>0</sup> = 1
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>n = 16
<strong>输出:</strong>true
<strong>解释:</strong>2<sup>4</sup> = 16
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>n = 3
<strong>输出:</strong>false
</pre>
<p><strong>示例 4:</strong></p>
<pre>
<strong>输入:</strong>n = 4
<strong>输出:</strong>true
</pre>
<p><strong>示例 5:</strong></p>
<pre>
<strong>输入:</strong>n = 5
<strong>输出:</strong>false
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>-2<sup>31</sup> <= n <= 2<sup>31</sup> - 1</code></li>
</ul>
<p> </p>
<p><strong>进阶:</strong>你能够不使用循环/递归解决此问题吗?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isPowerOfTwo(int n)
{
int cur = 0;
for (int i = 0; i < 31; i++)
{
cur += (n >> i) & 1;
}
return n > 0 && cur == 1;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-541c93e32cbc42deb82573d4759671e5",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "147ed9774f9941238c0c45a42cb896cc",
"author": "csdn.net",
"keywords": "栈,设计,队列",
"notebook_enable": true
}
\ No newline at end of file
# 用栈实现队列
<p>请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(<code>push</code><code>pop</code><code>peek</code><code>empty</code>):</p>
<p>实现 <code>MyQueue</code> 类:</p>
<ul>
<li><code>void push(int x)</code> 将元素 x 推到队列的末尾</li>
<li><code>int pop()</code> 从队列的开头移除并返回元素</li>
<li><code>int peek()</code> 返回队列开头的元素</li>
<li><code>boolean empty()</code> 如果队列为空,返回 <code>true</code> ;否则,返回 <code>false</code></li>
</ul>
<p> </p>
<p><strong>说明:</strong></p>
<ul>
<li>你只能使用标准的栈操作 —— 也就是只有 <code>push to top</code><code>peek/pop from top</code><code>size</code>, 和 <code>is empty</code> 操作是合法的。</li>
<li>你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。</li>
</ul>
<p> </p>
<p><strong>进阶:</strong></p>
<ul>
<li>你能否实现每个操作均摊时间复杂度为 <code>O(1)</code> 的队列?换句话说,执行 <code>n</code> 个操作的总时间复杂度为 <code>O(n)</code> ,即使其中一个操作可能花费较长时间。</li>
</ul>
<p> </p>
<p><strong>示例:</strong></p>
<pre>
<strong>输入:</strong>
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
<strong>输出:</strong>
[null, null, null, 1, 1, false]
<strong>解释:</strong>
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
</pre>
<ul>
</ul>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= x <= 9</code></li>
<li>最多调用 <code>100</code><code>push</code><code>pop</code><code>peek</code><code>empty</code></li>
<li>假设所有操作都是有效的 (例如,一个空的队列不会调用 <code>pop</code> 或者 <code>peek</code> 操作)</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class MyQueue
{
public:
/** Initialize your data structure here. */
stack<int> a, b;
MyQueue()
{
}
/** Push element x to the back of queue. */
void push(int x)
{
while (!b.empty())
{
a.push(b.top());
b.pop();
}
b.push(x);
while (!a.empty())
{
b.push(a.top());
a.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop()
{
int res = b.top();
b.pop();
return res;
}
/** Get the front element. */
int peek()
{
return b.top();
}
/** Returns whether the queue is empty. */
bool empty()
{
return b.empty();
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-9416ddb972a34cf1aa8a10edf76ce65f",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "3fa672cdbfc84d7893fb5d42da794ab2",
"author": "csdn.net",
"keywords": "栈,递归,链表,双指针",
"notebook_enable": true
}
\ No newline at end of file
# 回文链表
<p>给你一个单链表的头节点 <code>head</code> ,请你判断该链表是否为回文链表。如果是,返回 <code>true</code> ;否则,返回 <code>false</code></p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg" style="width: 422px; height: 62px;" />
<pre>
<strong>输入:</strong>head = [1,2,2,1]
<strong>输出:</strong>true
</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg" style="width: 182px; height: 62px;" />
<pre>
<strong>输入:</strong>head = [1,2]
<strong>输出:</strong>false
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li>链表中节点数目在范围<code>[1, 10<sup>5</sup>]</code></li>
<li><code>0 &lt;= Node.val &lt;= 9</code></li>
</ul>
<p>&nbsp;</p>
<p><strong>进阶:</strong>你能否用&nbsp;<code>O(n)</code> 时间复杂度和 <code>O(1)</code> 空间复杂度解决此题?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
bool isPalindrome(ListNode *head)
{
vector<int> v;
while (head != NULL)
{
v.push_back(head->val);
head = head->next;
}
for (int i = 0; i < v.size(); i++)
{
if (v[i] != v[v.size() - i - 1])
return false;
}
return true;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-27db96ec9b784632b5e93fa1cec6df61",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "13e6888b14114d16b05c8513cbdde328",
"author": "csdn.net",
"keywords": "树,深度优先搜索,二叉搜索树,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 二叉搜索树的最近公共祖先
<p>给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。</p>
<p><a href="https://baike.baidu.com/item/%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88/8918834?fr=aladdin" target="_blank">百度百科</a>中最近公共祖先的定义为:&ldquo;对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(<strong>一个节点也可以是它自己的祖先</strong>)。&rdquo;</p>
<p>例如,给定如下二叉搜索树:&nbsp; root =&nbsp;[6,2,8,0,4,7,9,null,null,3,5]</p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/14/binarysearchtree_improved.png" style="height: 190px; width: 200px;"></p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
<strong>输出:</strong> 6
<strong>解释: </strong>节点 <code>2 </code>和节点 <code>8 </code>的最近公共祖先是 <code>6。</code>
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
<strong>输出:</strong> 2
<strong>解释: </strong>节点 <code>2</code> 和节点 <code>4</code> 的最近公共祖先是 <code>2</code>, 因为根据定义最近公共祖先节点可以为节点本身。</pre>
<p>&nbsp;</p>
<p><strong>说明:</strong></p>
<ul>
<li>所有节点的值都是唯一的。</li>
<li>p、q 为不同节点且均存在于给定的二叉搜索树中。</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
if (root == NULL)
return NULL;
if ((root->val > q->val) && (root->val > p->val))
return lowestCommonAncestor(root->left, p, q);
else if ((root->val < q->val) && (root->val < p->val))
return lowestCommonAncestor(root->right, p, q);
return root;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-b1b34d10555f424f9012194aff09f895",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "d79649cb8a834b20905d373e6708efce",
"author": "csdn.net",
"keywords": "树,深度优先搜索,广度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 对称二叉树
<p>给定一个二叉树,检查它是否是镜像对称的。</p>
<p>&nbsp;</p>
<p>例如,二叉树&nbsp;<code>[1,2,2,3,4,4,3]</code> 是对称的。</p>
<pre> 1
/ \
2 2
/ \ / \
3 4 4 3
</pre>
<p>&nbsp;</p>
<p>但是下面这个&nbsp;<code>[1,2,2,null,3,null,3]</code> 则不是镜像对称的:</p>
<pre> 1
/ \
2 2
\ \
3 3
</pre>
<p>&nbsp;</p>
<p><strong>进阶:</strong></p>
<p>你可以运用递归和迭代两种方法解决这个问题吗?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
bool haha(TreeNode *l, TreeNode *r)
{
if (!l && !r)
return true;
if (!l || !r)
return false;
if (l->val != r->val)
return false;
return haha(l->right, r->left) & haha(l->left, r->right);
}
bool isSymmetric(TreeNode *root)
{
if (!root)
return true;
return haha(root->left, root->right);
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-b34e8ed950f64727b2b4653b8433dc22",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "32cd436081f24793a212d2ea766f0ba1",
"author": "csdn.net",
"keywords": "树,深度优先搜索,广度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 二叉树的最大深度
<p>给定一个二叉树,找出其最大深度。</p>
<p>二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。</p>
<p><strong>说明:</strong>&nbsp;叶子节点是指没有子节点的节点。</p>
<p><strong>示例:</strong><br>
给定二叉树 <code>[3,9,20,null,null,15,7]</code></p>
<pre> 3
/ \
9 20
/ \
15 7</pre>
<p>返回它的最大深度&nbsp;3 。</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int maxDepth(TreeNode *root)
{
int depth = 0;
if (root == NULL)
{
return 0;
}
else
{
depth = max(maxDepth(root->left), maxDepth(root->right));
return 1 + depth;
}
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-9c576c7dcc0247e2ae923077462c4baa",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "aaa09326cb5644cc8065da1415bc2c12",
"author": "csdn.net",
"keywords": "树,深度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 求根节点到叶节点数字之和
给你一个二叉树的根节点 <code>root</code> ,树中每个节点都存放有一个 <code>0</code><code>9</code> 之间的数字。
<div class="original__bRMd">
<div>
<p>每条从根节点到叶节点的路径都代表一个数字:</p>
<ul>
<li>例如,从根节点到叶节点的路径 <code>1 -> 2 -> 3</code> 表示数字 <code>123</code></li>
</ul>
<p>计算从根节点到叶节点生成的 <strong>所有数字之和</strong></p>
<p><strong>叶节点</strong> 是指没有子节点的节点。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg" style="width: 212px; height: 182px;" />
<pre>
<strong>输入:</strong>root = [1,2,3]
<strong>输出:</strong>25
<strong>解释:</strong>
从根到叶子节点路径 <code>1->2</code> 代表数字 <code>12</code>
从根到叶子节点路径 <code>1->3</code> 代表数字 <code>13</code>
因此,数字总和 = 12 + 13 = <code>25</code></pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg" style="width: 292px; height: 302px;" />
<pre>
<strong>输入:</strong>root = [4,9,0,5,1]
<strong>输出:</strong>1026
<strong>解释:</strong>
从根到叶子节点路径 <code>4->9->5</code> 代表数字 495
从根到叶子节点路径 <code>4->9->1</code> 代表数字 491
从根到叶子节点路径 <code>4->0</code> 代表数字 40
因此,数字总和 = 495 + 491 + 40 = <code>1026</code>
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点的数目在范围 <code>[1, 1000]</code></li>
<li><code>0 <= Node.val <= 9</code></li>
<li>树的深度不超过 <code>10</code></li>
</ul>
</div>
</div>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int sumNumbers(TreeNode *root)
{
if (root == nullptr)
return 0;
int result = 0;
vector<int> num;
vector<int> temp;
digui(root, &num, &temp);
for (int i = 0; i < num.size(); i++)
{
result = result + num[i];
}
return result;
}
void digui(TreeNode *root, vector<int> *num, vector<int> *temp)
{
temp->push_back(root->val);
if (root->left == nullptr && root->right == nullptr)
{
int sum = 0;
for (int i = temp->size() - 1; i >= 0; i--)
{
/*if (i==0 && (*temp)[0]==0) {
continue;
}*/
int howi = (*temp)[i];
sum = sum + howi * pow(10, (temp->size() - i - 1));
}
num->push_back(sum);
temp->pop_back();
return;
}
if (root->left)
digui(root->left, num, temp);
if (root->right)
digui(root->right, num, temp);
temp->pop_back();
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-0c3ef2e1bd1242338188dd04275436e9",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "da6922e6926a4e50899352935ffd9566",
"author": "csdn.net",
"keywords": "深度优先搜索,广度优先搜索,并查集,数组,矩阵",
"notebook_enable": true
}
\ No newline at end of file
# 被围绕的区域
给你一个 <code>m x n</code> 的矩阵 <code>board</code> ,由若干字符 <code>'X'</code><code>'O'</code> ,找到所有被 <code>'X'</code> 围绕的区域,并将这些区域里所有的 <code>'O'</code><code>'X'</code> 填充。
<div class="original__bRMd">
<div>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/xogrid.jpg" style="width: 550px; height: 237px;" />
<pre>
<strong>输入:</strong>board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
<strong>输出:</strong>[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
<strong>解释:</strong>被围绕的区间不会存在于边界上,换句话说,任何边界上的 <code>'O'</code> 都不会被填充为 <code>'X'</code>。 任何不在边界上,或不与边界上的 <code>'O'</code> 相连的 <code>'O'</code> 最终都会被填充为 <code>'X'</code>。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>board = [["X"]]
<strong>输出:</strong>[["X"]]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>m == board.length</code></li>
<li><code>n == board[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>board[i][j]</code><code>'X'</code><code>'O'</code></li>
</ul>
</div>
</div>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int m, n;
void solve(vector<vector<char>> &board)
{
m = board.size();
if (!m)
return;
n = board[0].size();
if (!n)
return;
for (int i = 0; i < m; ++i)
{
if (i == 0 || i == m - 1)
{
for (int j = 0; j < n; ++j)
{
if (board[i][j] == 'O')
dfs(board, i, j);
}
}
else
{
if (board[i][0] == 'O')
dfs(board, i, 0);
if (board[i][n - 1] == 'O')
dfs(board, i, n - 1);
}
}
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
{
if (board[i][j] == 'A')
board[i][j] = 'O';
else
board[i][j] = 'X';
}
}
void dfs(vector<vector<char>> &board, int i, int j)
{
board[i][j] = 'A';
if (i - 1 < m && i - 1 >= 0 && j < n && j >= 0 && board[i - 1][j] == 'O')
{
dfs(board, i - 1, j);
}
if (i + 1 < m && i + 1 >= 0 && j < n && j >= 0 && board[i + 1][j] == 'O')
{
dfs(board, i + 1, j);
}
if (i < m && i >= 0 && j - 1 < n && j - 1 >= 0 && board[i][j - 1] == 'O')
{
dfs(board, i, j - 1);
}
if (i < m && i >= 0 && j + 1 < n && j + 1 >= 0 && board[i][j + 1] == 'O')
{
dfs(board, i, j + 1);
}
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-6595ec837a47451bb033b3d82cbcf542",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "e58bd889e1d14d47b472202ff1401855",
"author": "csdn.net",
"keywords": "字符串,动态规划,回溯",
"notebook_enable": true
}
\ No newline at end of file
# 分割回文串
<p>给你一个字符串 <code>s</code>,请你将<em> </em><code>s</code><em> </em>分割成一些子串,使每个子串都是 <strong>回文串</strong> 。返回 <code>s</code> 所有可能的分割方案。</p>
<p><strong>回文串</strong> 是正着读和反着读都一样的字符串。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>s = "aab"
<strong>输出:</strong>[["a","a","b"],["aa","b"]]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>s = "a"
<strong>输出:</strong>[["a"]]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= s.length <= 16</code></li>
<li><code>s</code> 仅由小写英文字母组成</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isPali(string s)
{
for (int i = 0; i < s.length() / 2; i++)
if (s[i] != s[s.length() - i - 1])
return false;
return true;
}
void dfs(vector<vector<string>> &ans, vector<string> &tmp, int n, string s)
{
if (n == s.length())
{
ans.push_back(tmp);
return;
}
for (int i = n; i < s.length(); i++)
{
if (isPali(s.substr(n, i - n + 1)))
{
tmp.push_back(s.substr(n, i - n + 1));
dfs(ans, tmp, i + 1, s);
tmp.pop_back();
}
}
}
vector<vector<string>> partition(string s)
{
vector<vector<string>> ans;
vector<string> tmp;
dfs(ans, tmp, 0, s);
return ans;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-2e0242542523489684fe462e57e5dc2d",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "bf408a7721784878b90fb71b52238074",
"author": "csdn.net",
"keywords": "深度优先搜索,广度优先搜索,图,哈希表",
"notebook_enable": true
}
\ No newline at end of file
# 克隆图
<p>给你无向&nbsp;<strong><a href="https://baike.baidu.com/item/连通图/6460995?fr=aladdin" target="_blank">连通</a>&nbsp;</strong>图中一个节点的引用,请你返回该图的&nbsp;<a href="https://baike.baidu.com/item/深拷贝/22785317?fr=aladdin" target="_blank"><strong>深拷贝</strong></a>(克隆)。</p>
<p>图中的每个节点都包含它的值 <code>val</code><code>int</code>) 和其邻居的列表(<code>list[Node]</code>)。</p>
<pre>class Node {
public int val;
public List&lt;Node&gt; neighbors;
}</pre>
<p>&nbsp;</p>
<p><strong>测试用例格式:</strong></p>
<p>简单起见,每个节点的值都和它的索引相同。例如,第一个节点值为 1(<code>val = 1</code>),第二个节点值为 2(<code>val = 2</code>),以此类推。该图在测试用例中使用邻接列表表示。</p>
<p><strong>邻接列表</strong> 是用于表示有限图的无序列表的集合。每个列表都描述了图中节点的邻居集。</p>
<p>给定节点将始终是图中的第一个节点(值为 1)。你必须将&nbsp;<strong>给定节点的拷贝&nbsp;</strong>作为对克隆图的引用返回。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/02/01/133_clone_graph_question.png" style="height: 500px; width: 500px;"></p>
<pre><strong>输入:</strong>adjList = [[2,4],[1,3],[2,4],[1,3]]
<strong>输出:</strong>[[2,4],[1,3],[2,4],[1,3]]
<strong>解释:
</strong>图中有 4 个节点。
节点 1 的值是 1,它有两个邻居:节点 2 和 4 。
节点 2 的值是 2,它有两个邻居:节点 1 和 3 。
节点 3 的值是 3,它有两个邻居:节点 2 和 4 。
节点 4 的值是 4,它有两个邻居:节点 1 和 3 。
</pre>
<p><strong>示例 2:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/02/01/graph.png" style="height: 148px; width: 163px;"></p>
<pre><strong>输入:</strong>adjList = [[]]
<strong>输出:</strong>[[]]
<strong>解释:</strong>输入包含一个空列表。该图仅仅只有一个值为 1 的节点,它没有任何邻居。
</pre>
<p><strong>示例 3:</strong></p>
<pre><strong>输入:</strong>adjList = []
<strong>输出:</strong>[]
<strong>解释:</strong>这个图是空的,它不含任何节点。
</pre>
<p><strong>示例 4:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/02/01/graph-1.png" style="height: 133px; width: 272px;"></p>
<pre><strong>输入:</strong>adjList = [[2],[1]]
<strong>输出:</strong>[[2],[1]]</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ol>
<li>节点数不超过 100 。</li>
<li>每个节点值&nbsp;<code>Node.val</code> 都是唯一的,<code>1 &lt;= Node.val &lt;= 100</code></li>
<li>无向图是一个<a href="https://baike.baidu.com/item/简单图/1680528?fr=aladdin" target="_blank">简单图</a>,这意味着图中没有重复的边,也没有自环。</li>
<li>由于图是无向的,如果节点 <em>p</em> 是节点 <em>q</em> 的邻居,那么节点 <em>q</em> 也必须是节点 <em>p</em>&nbsp;的邻居。</li>
<li>图是连通图,你可以从给定节点访问到所有节点。</li>
</ol>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
vector<Node *> neighbors;
Node() {}
Node(int _val, vector<Node *> _neighbors)
{
val = _val;
neighbors = _neighbors;
}
};
class Solution
{
public:
Node *cloneGraph(Node *node)
{
unordered_map<Node *, Node *> m;
return helper(node, m);
}
Node *helper(Node *node, unordered_map<Node *, Node *> &m)
{
if (!node)
return NULL;
if (m.count(node))
return m[node];
Node *clone = new Node(node->val);
m[node] = clone;
for (Node *neighbor : node->neighbors)
{
clone->neighbors.push_back(helper(neighbor, m));
}
return clone;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-75dace4205f44a3598936beb6e9bab7a",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "1f2b3e0e87e44f42a819c33feb21cce4",
"author": "csdn.net",
"keywords": "贪心,数组",
"notebook_enable": true
}
\ No newline at end of file
# 加油站
<p>在一条环路上有&nbsp;<em>N</em>&nbsp;个加油站,其中第&nbsp;<em>i</em>&nbsp;个加油站有汽油&nbsp;<code>gas[i]</code><em>&nbsp;</em>升。</p>
<p>你有一辆油箱容量无限的的汽车,从第<em> i </em>个加油站开往第<em> i+1&nbsp;</em>个加油站需要消耗汽油&nbsp;<code>cost[i]</code><em>&nbsp;</em>升。你从其中的一个加油站出发,开始时油箱为空。</p>
<p>如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。</p>
<p><strong>说明:</strong>&nbsp;</p>
<ul>
<li>如果题目有解,该答案即为唯一答案。</li>
<li>输入数组均为非空数组,且长度相同。</li>
<li>输入数组中的元素均为非负数。</li>
</ul>
<p><strong>示例&nbsp;1:</strong></p>
<pre><strong>输入:</strong>
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
<strong>输出:</strong> 3
<strong>解释:
</strong>从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油
开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油
开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油
开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油
开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油
开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。
因此,3 可为起始索引。</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong>
gas = [2,3,4]
cost = [3,4,3]
<strong>输出:</strong> -1
<strong>解释:
</strong>你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。
我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油
开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油
开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油
你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。
因此,无论怎样,你都不可能绕环路行驶一周。</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
int index = 0;
int sum = 0;
int csum = 0;
for (int i = 0; i < gas.size(); i++)
{
int temp = gas[i] - cost[i];
sum += temp;
if (csum > 0)
{
csum += gas[i] - cost[i];
}
else
{
csum = gas[i] - cost[i];
index = i;
}
}
return sum >= 0 ? index : -1;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-0de614ddd4a841aca80d2037ae64bfe9",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "afa57be04ea148dcbe59f3b4b37f9e99",
"author": "csdn.net",
"keywords": "位运算,数组",
"notebook_enable": true
}
\ No newline at end of file
# 只出现一次的数字 II
<p>给你一个整数数组 <code>nums</code> ,除某个元素仅出现 <strong>一次</strong> 外,其余每个元素都恰出现 <strong>三次 。</strong>请你找出并返回那个只出现了一次的元素。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>nums = [2,2,3,2]
<strong>输出:</strong>3
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [0,1,0,1,0,1,99]
<strong>输出:</strong>99
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>nums</code> 中,除某个元素仅出现 <strong>一次</strong> 外,其余每个元素都恰出现 <strong>三次</strong></li>
</ul>
<p> </p>
<p><strong>进阶:</strong>你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int singleNumber(vector<int> &nums)
{
sort(nums.begin(), nums.end());
int res = 0;
int i = 0;
for (int j = 1; j < nums.size(); j++)
{
if (nums[j] != nums[i])
{
if (j - i == 1)
{
res = nums[i];
break;
}
else
{
i = j;
}
}
}
if (i == nums.size() - 1)
{
res = nums[i];
}
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-ee972a8c3ad94ef4937a12be5da23849",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "504efc590cbb42e49757004b04b3e4e8",
"author": "csdn.net",
"keywords": "哈希表,链表",
"notebook_enable": true
}
\ No newline at end of file
# 复制带随机指针的链表
<p>给你一个长度为 <code>n</code> 的链表,每个节点包含一个额外增加的随机指针 <code>random</code> ,该指针可以指向链表中的任何节点或空节点。</p>
<p>构造这个链表的 <strong><a href="https://baike.baidu.com/item/深拷贝/22785317?fr=aladdin" target="_blank">深拷贝</a></strong>。 深拷贝应该正好由 <code>n</code><strong>全新</strong> 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 <code>next</code> 指针和 <code>random</code> 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。<strong>复制链表中的指针都不应指向原链表中的节点 </strong></p>
<p>例如,如果原链表中有 <code>X</code><code>Y</code> 两个节点,其中 <code>X.random --> Y</code> 。那么在复制链表中对应的两个节点 <code>x</code><code>y</code> ,同样有 <code>x.random --> y</code></p>
<p>返回复制链表的头节点。</p>
<p>用一个由 <code>n</code> 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 <code>[val, random_index]</code> 表示:</p>
<ul>
<li><code>val</code>:一个表示 <code>Node.val</code> 的整数。</li>
<li><code>random_index</code>:随机指针指向的节点索引(范围从 <code>0</code> 到 <code>n-1</code>);如果不指向任何节点,则为  <code>null</code> 。</li>
</ul>
<p>你的代码 <strong></strong> 接受原链表的头节点 <code>head</code> 作为传入参数。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/01/09/e1.png" style="height: 138px; width: 680px;" /></p>
<pre>
<strong>输入:</strong>head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
<strong>输出:</strong>[[7,null],[13,0],[11,4],[10,2],[1,0]]
</pre>
<p><strong>示例 2:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/01/09/e2.png" style="height: 111px; width: 680px;" /></p>
<pre>
<strong>输入:</strong>head = [[1,1],[2,1]]
<strong>输出:</strong>[[1,1],[2,1]]
</pre>
<p><strong>示例 3:</strong></p>
<p><strong><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/01/09/e3.png" style="height: 119px; width: 680px;" /></strong></p>
<pre>
<strong>输入:</strong>head = [[3,null],[3,0],[3,null]]
<strong>输出:</strong>[[3,null],[3,0],[3,null]]
</pre>
<p><strong>示例 4:</strong></p>
<pre>
<strong>输入:</strong>head = []
<strong>输出:</strong>[]
<strong>解释:</strong>给定的链表为空(空指针),因此返回 null。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 <= n <= 1000</code></li>
<li><code>-10000 <= Node.val <= 10000</code></li>
<li><code>Node.random</code> 为空(null)或指向链表中的节点。</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node *next;
Node *random;
Node() {}
Node(int _val, Node *_next, Node *_random)
{
val = _val;
next = _next;
random = _random;
}
};
class Solution
{
public:
Node *copyRandomList(Node *head)
{
std::map<Node *, int> node_map;
std::vector<Node *> node_vec;
Node *ptr = head;
int i = 0;
while (ptr)
{
node_vec.push_back(new Node(ptr->val, NULL, NULL));
node_map[ptr] = i;
ptr = ptr->next;
i++;
}
node_vec.push_back(0);
ptr = head;
i = 0;
while (ptr)
{
node_vec[i]->next = node_vec[i + 1];
if (ptr->random)
{
int id = node_map[ptr->random];
node_vec[i]->random = node_vec[id];
}
ptr = ptr->next;
i++;
}
return node_vec[0];
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-7ab771c2a0454a8d88061ebc100eb41e",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "a999e9a2aa0e4d8f945cfe6efca6fab9",
"author": "csdn.net",
"keywords": "字典树,记忆化搜索,哈希表,字符串,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 单词拆分
<p>给定一个<strong>非空</strong>字符串 <em>s</em> 和一个包含<strong>非空</strong>单词的列表 <em>wordDict</em>,判定&nbsp;<em>s</em> 是否可以被空格拆分为一个或多个在字典中出现的单词。</p>
<p><strong>说明:</strong></p>
<ul>
<li>拆分时可以重复使用字典中的单词。</li>
<li>你可以假设字典中没有重复的单词。</li>
</ul>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> s = &quot;leetcode&quot;, wordDict = [&quot;leet&quot;, &quot;code&quot;]
<strong>输出:</strong> true
<strong>解释:</strong> 返回 true 因为 &quot;leetcode&quot; 可以被拆分成 &quot;leet code&quot;
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> s = &quot;applepenapple&quot;, wordDict = [&quot;apple&quot;, &quot;pen&quot;]
<strong>输出:</strong> true
<strong>解释:</strong> 返回 true 因为 <code>&quot;</code>applepenapple<code>&quot;</code> 可以被拆分成 <code>&quot;</code>apple pen apple<code>&quot;</code>
&nbsp; 注意你可以重复使用字典中的单词。
</pre>
<p><strong>示例 3:</strong></p>
<pre><strong>输入:</strong> s = &quot;catsandog&quot;, wordDict = [&quot;cats&quot;, &quot;dog&quot;, &quot;sand&quot;, &quot;and&quot;, &quot;cat&quot;]
<strong>输出:</strong> false
</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool wordBreak(string s, vector<string> &wordDict)
{
map<string, int> tmp;
for (int i = 0; i < wordDict.size(); i++)
{
tmp[wordDict[i]]++;
}
int n = s.length();
vector<bool> res(n + 1, false);
res[0] = true;
for (int i = 0; i <= n; i++)
{
for (int j = 0; j < i; j++)
{
if (res[j] && tmp[s.substr(j, i - j)])
{
res[i] = true;
break;
}
}
}
return res[n];
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-c86e8718d6a14cbcb86586cfeded8a86",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "c57e84df7922455895cfc253eff07450",
"author": "csdn.net",
"keywords": "哈希表,链表,双指针",
"notebook_enable": true
}
\ No newline at end of file
# 环形链表 II
<p>给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 <code>null</code></p>
<p>为了表示给定链表中的环,我们使用整数 <code>pos</code> 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 <code>pos</code><code>-1</code>,则在该链表中没有环。<strong>注意,<code>pos</code> 仅仅是用于标识环的情况,并不会作为参数传递到函数中。</strong></p>
<p><strong>说明:</strong>不允许修改给定的链表。</p>
<p><strong>进阶:</strong></p>
<ul>
<li>你是否可以使用 <code>O(1)</code> 空间解决此题?</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist.png" style="height: 97px; width: 300px;" /></p>
<pre>
<strong>输入:</strong>head = [3,2,0,-4], pos = 1
<strong>输出:</strong>返回索引为 1 的链表节点
<strong>解释:</strong>链表中有一个环,其尾部连接到第二个节点。
</pre>
<p><strong>示例 2:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test2.png" style="height: 74px; width: 141px;" /></p>
<pre>
<strong>输入:</strong>head = [1,2], pos = 0
<strong>输出:</strong>返回索引为 0 的链表节点
<strong>解释:</strong>链表中有一个环,其尾部连接到第一个节点。
</pre>
<p><strong>示例 3:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test3.png" style="height: 45px; width: 45px;" /></p>
<pre>
<strong>输入:</strong>head = [1], pos = -1
<strong>输出:</strong>返回 null
<strong>解释:</strong>链表中没有环。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>链表中节点的数目范围在范围 <code>[0, 10<sup>4</sup>]</code></li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
<li><code>pos</code> 的值为 <code>-1</code> 或者链表中的一个有效索引</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
ListNode *slow, *fast, *p;
slow = fast = p = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
while (p != slow)
{
p = p->next;
slow = slow->next;
}
return p;
}
}
return nullptr;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-0f4fa52ce6504716996db85e4c9e493a",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "f5a81fc3e5a040ea8e0429a1e3cf941f",
"author": "csdn.net",
"keywords": "栈,递归,链表,双指针",
"notebook_enable": true
}
\ No newline at end of file
# 重排链表
<p>给定一个单链表 <code>L</code><em> </em>的头节点 <code>head</code> ,单链表 <code>L</code> 表示为:</p>
<p><code> L<sub></sub>→ L<sub></sub>→ … → L<sub>n-1 </sub>→ L<sub></sub></code><br />
请将其重新排列后变为:</p>
<p><code>L<sub></sub>→ L<sub></sub>→ L<sub></sub>→ L<sub>n-1 </sub>→ L<sub></sub>→ L<sub>n-2 </sub>→ …</code></p>
<p>不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://pic.leetcode-cn.com/1626420311-PkUiGI-image.png" style="width: 240px; " /></p>
<pre>
<strong>输入: </strong>head = [1,2,3,4]
<strong>输出: </strong>[1,4,2,3]</pre>
<p><strong>示例 2:</strong></p>
<p><img alt="" src="https://pic.leetcode-cn.com/1626420320-YUiulT-image.png" style="width: 320px; " /></p>
<pre>
<strong>输入: </strong>head = [1,2,3,4,5]
<strong>输出: </strong>[1,5,2,4,3]</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>链表的长度范围为 <code>[1, 5 * 10<sup>4</sup>]</code></li>
<li><code>1 <= node.val <= 1000</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
void reorderList(ListNode *head)
{
ListNode *l1 = head, *l2 = head;
ListNode *tep = head;
int len = 0;
while (tep)
{
len++;
tep = tep->next;
}
if (len <= 2)
return;
int len1 = len / 2 + len % 2;
int len2 = len / 2;
for (int i = 0; i < len1 - 1; i++)
{
head = head->next;
}
l2 = head->next;
head->next = nullptr;
head = l1;
stack<ListNode *> stk;
while (l2)
{
stk.push(l2);
l2 = l2->next;
}
while (!stk.empty())
{
tep = stk.top();
stk.pop();
tep->next = l1->next;
l1->next = tep;
l1 = tep->next;
}
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-a60d5b2274744417bc065e034719adb5",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "6925248d8d4b4971ace262cdfc82e08b",
"author": "csdn.net",
"keywords": "设计,哈希表,链表,双向链表",
"notebook_enable": true
}
\ No newline at end of file
# LRU 缓存机制
<div class="title__3Vvk">运用你所掌握的数据结构,设计和实现一个  <a href="https://baike.baidu.com/item/LRU" target="_blank">LRU (最近最少使用) 缓存机制</a></div>
<div class="original__bRMd">
<div>
<p>实现 <code>LRUCache</code> 类:</p>
<ul>
<li><code>LRUCache(int capacity)</code> 以正整数作为容量 <code>capacity</code> 初始化 LRU 缓存</li>
<li><code>int get(int key)</code> 如果关键字 <code>key</code> 存在于缓存中,则返回关键字的值,否则返回 <code>-1</code></li>
<li><code>void put(int key, int value)</code> 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。</li>
</ul>
<p> </p>
</div>
</div>
<p><strong>进阶</strong>:你是否可以在 <code>O(1)</code> 时间复杂度内完成这两种操作?</p>
<p> </p>
<p><strong>示例:</strong></p>
<pre>
<strong>输入</strong>
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
<strong>输出</strong>
[null, null, null, 1, null, -1, null, -1, 3, 4]
<strong>解释</strong>
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1); // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2); // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1); // 返回 -1 (未找到)
lRUCache.get(3); // 返回 3
lRUCache.get(4); // 返回 4
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= capacity <= 3000</code></li>
<li><code>0 <= key <= 10000</code></li>
<li><code>0 <= value <= 10<sup>5</sup></code></li>
<li>最多调用 <code>2 * 10<sup>5</sup></code><code>get</code><code>put</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class LRUCache
{
private:
int _cap;
list<pair<int, int>> cache;
unordered_map<int, list<pair<int, int>>::iterator> umap;
public:
LRUCache(int capacity)
{
_cap = capacity;
}
int get(int key)
{
auto iter = umap.find(key);
if (iter == umap.end())
return -1;
pair<int, int> kv = *umap[key];
cache.erase(umap[key]);
cache.push_front(kv);
umap[key] = cache.begin();
return kv.second;
}
void put(int key, int value)
{
auto iter = umap.find(key);
if (iter != umap.end())
{
cache.erase(umap[key]);
cache.push_front(make_pair(key, value));
umap[key] = cache.begin();
return;
}
if (cache.size() == _cap)
{
auto iter = cache.back();
umap.erase(iter.first);
cache.pop_back();
cache.push_front(make_pair(key, value));
umap[key] = cache.begin();
}
else
{
cache.push_front(make_pair(key, value));
umap[key] = cache.begin();
}
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-36ed7137f34d4fd2b2b5e101ce9756bb",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "bc206a68afdd49898d978634851b9566",
"author": "csdn.net",
"keywords": "链表,排序",
"notebook_enable": true
}
\ No newline at end of file
# 对链表进行插入排序
<p>对链表进行插入排序。</p>
<p><img alt="" src="https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif"><br>
<small>插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。<br>
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。</small></p>
<p>&nbsp;</p>
<p><strong>插入排序算法:</strong></p>
<ol>
<li>插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。</li>
<li>每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。</li>
<li>重复直到所有输入数据插入完为止。</li>
</ol>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> 4-&gt;2-&gt;1-&gt;3
<strong>输出:</strong> 1-&gt;2-&gt;3-&gt;4
</pre>
<p><strong>示例&nbsp;2:</strong></p>
<pre><strong>输入:</strong> -1-&gt;5-&gt;3-&gt;4-&gt;0
<strong>输出:</strong> -1-&gt;0-&gt;3-&gt;4-&gt;5
</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *insertionSortList(ListNode *head)
{
ListNode *dummy = new ListNode(0, head);
ListNode
*prev = dummy,
*lastSorted = head,
*curr = head->next;
while (curr)
{
lastSorted->next = curr->next;
curr->next = prev->next;
prev->next = curr;
curr = lastSorted->next;
}
return dummy->next;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-0eb990da86e340998c215d3a1d8aa859",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "0f14c22af5474598bd0f688223cb0c68",
"author": "csdn.net",
"keywords": "链表,双指针,分治,排序,归并排序",
"notebook_enable": true
}
\ No newline at end of file
# 排序链表
<p>给你链表的头结点 <code>head</code> ,请将其按 <strong>升序</strong> 排列并返回 <strong>排序后的链表</strong></p>
<p><b>进阶:</b></p>
<ul>
<li>你可以在 <code>O(n log n)</code> 时间复杂度和常数级空间复杂度下,对链表进行排序吗?</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg" style="width: 302px; "/>
<pre>
<b>输入:</b>head = [4,2,1,3]
<b>输出:</b>[1,2,3,4]
</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg" style="width: 402px; " />
<pre>
<b>输入:</b>head = [-1,5,3,4,0]
<b>输出:</b>[-1,0,3,4,5]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<b>输入:</b>head = []
<b>输出:</b>[]
</pre>
<p> </p>
<p><b>提示:</b></p>
<ul>
<li>链表中节点的数目在范围 <code>[0, 5 * 10<sup>4</sup>]</code> 内</li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *sortList(ListNode *head)
{
return mergesort(head);
}
ListNode *mergesort(ListNode *node)
{
if (!node || !node->next)
return node;
ListNode *fast = node;
ListNode *slow = node;
ListNode *brek = node;
while (fast && fast->next)
{
fast = fast->next->next;
brek = slow;
slow = slow->next;
}
brek->next = nullptr;
ListNode *l1 = mergesort(node);
ListNode *l2 = mergesort(slow);
return merge(l1, l2);
}
ListNode *merge(ListNode *l1, ListNode *l2)
{
if (l1 == NULL)
{
return l2;
}
if (l2 == NULL)
{
return l1;
}
if (l1->val < l2->val)
{
l1->next = merge(l1->next, l2);
return l1;
}
else
{
l2->next = merge(l2->next, l1);
return l2;
}
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-f69b5024f7ea4a72811393706d30e524",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "d6df7d868e7648678eb11fff0e8eda92",
"author": "csdn.net",
"keywords": "栈,数组,数学",
"notebook_enable": true
}
\ No newline at end of file
# 逆波兰表达式求值
<p>根据<a href="https://baike.baidu.com/item/%E9%80%86%E6%B3%A2%E5%85%B0%E5%BC%8F/128437" target="_blank"> 逆波兰表示法</a>,求表达式的值。</p>
<p>有效的算符包括 <code>+</code><code>-</code><code>*</code><code>/</code> 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。</p>
<p> </p>
<p><strong>说明:</strong></p>
<ul>
<li>整数除法只保留整数部分。</li>
<li>给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>tokens = ["2","1","+","3","*"]
<strong>输出:</strong>9
<strong>解释:</strong>该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>tokens = ["4","13","5","/","+"]
<strong>输出:</strong>6
<strong>解释:</strong>该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
<strong>输出:</strong>22
<strong>解释:</strong>
该算式转化为常见的中缀算术表达式为:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= tokens.length <= 10<sup>4</sup></code></li>
<li><code>tokens[i]</code> 要么是一个算符(<code>"+"</code><code>"-"</code><code>"*"</code><code>"/"</code>),要么是一个在范围 <code>[-200, 200]</code> 内的整数</li>
</ul>
<p> </p>
<p><strong>逆波兰表达式:</strong></p>
<p>逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。</p>
<ul>
<li>平常使用的算式则是一种中缀表达式,如 <code>( 1 + 2 ) * ( 3 + 4 )</code></li>
<li>该算式的逆波兰表达式写法为 <code>( ( 1 2 + ) ( 3 4 + ) * )</code></li>
</ul>
<p>逆波兰表达式主要有以下两个优点:</p>
<ul>
<li>去掉括号后表达式无歧义,上式即便写成 <code>1 2 + 3 4 + * </code>也可以依据次序计算出正确结果。</li>
<li>适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中。</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
stack<int> num;
for (int i = 0; i < tokens.size(); ++i)
{
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
{
int j;
int a = num.top();
num.pop();
int b = num.top();
num.pop();
if (tokens[i] == "+")
j = b + a;
else if (tokens[i] == "-")
j = b - a;
else if (tokens[i] == "*")
j = b * a;
else
j = b / a;
num.push(j);
}
else
{
num.push(stoi(tokens[i]));
}
}
return num.top();
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-05046db437fa4f03bd4e5f082a388673",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "cd5c9fb0e79a4ff6814d13a0db4ce918",
"author": "csdn.net",
"keywords": "双指针,字符串",
"notebook_enable": true
}
\ No newline at end of file
# 翻转字符串里的单词
<p>给你一个字符串 <code>s</code> ,逐个翻转字符串中的所有 <strong>单词</strong></p>
<p><strong>单词</strong> 是由非空格字符组成的字符串。<code>s</code> 中使用至少一个空格将字符串中的 <strong>单词</strong> 分隔开。</p>
<p>请你返回一个翻转 <code>s</code> 中单词顺序并用单个空格相连的字符串。</p>
<p><strong>说明:</strong></p>
<ul>
<li>输入字符串 <code>s</code> 可以在前面、后面或者单词间包含多余的空格。</li>
<li>翻转后单词间应当仅用一个空格分隔。</li>
<li>翻转后的字符串中不应包含额外的空格。</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>s = "<code>the sky is blue</code>"
<strong>输出:</strong>"<code>blue is sky the</code>"
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>s = "  hello world  "
<strong>输出:</strong>"world hello"
<strong>解释:</strong>输入字符串可以在前面或者后面包含多余的空格,但是翻转后的字符不能包括。
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>s = "a good   example"
<strong>输出:</strong>"example good a"
<strong>解释:</strong>如果两个单词间有多余的空格,将翻转后单词间的空格减少到只含一个。
</pre>
<p><strong>示例 4:</strong></p>
<pre>
<strong>输入:</strong>s = " Bob Loves Alice "
<strong>输出:</strong>"Alice Loves Bob"
</pre>
<p><strong>示例 5:</strong></p>
<pre>
<strong>输入:</strong>s = "Alice does not even like bob"
<strong>输出:</strong>"bob like even not does Alice"
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> 包含英文大小写字母、数字和空格 <code>' '</code></li>
<li><code>s</code><strong>至少存在一个</strong> 单词</li>
</ul>
<ul>
</ul>
<p> </p>
<p><strong>进阶:</strong></p>
<ul>
<li>请尝试使用 <code><em>O</em>(1)</code> 额外空间复杂度的原地解法。</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
string reverseWords(string s)
{
splitStr(s);
return joinStr();
}
private:
void splitStr(string s)
{
if (s == "")
return;
int len = s.length();
string tmp = "";
for (int i = 0; i < len; i++)
{
if (s[i] == ' ' && tmp != "")
{
myStack.push(tmp);
tmp = "";
continue;
}
if (s[i] == ' ')
continue;
tmp += s[i];
}
if (tmp != "")
myStack.push(tmp);
return;
}
string joinStr()
{
if (myStack.empty())
return "";
string s = "";
while (!myStack.empty())
{
s += myStack.top();
s += " ";
myStack.pop();
}
return s.substr(0, s.length() - 1);
}
stack<string> myStack;
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-e33c5f27e8214636a42bc8cf443ac7dc",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "5aef5bb4e105434789d7066ad7b6d9c5",
"author": "csdn.net",
"keywords": "数组,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 乘积最大子数组
<p>给你一个整数数组 <code>nums</code>&nbsp;,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> [2,3,-2,4]
<strong>输出:</strong> <code>6</code>
<strong>解释:</strong>&nbsp;子数组 [2,3] 有最大乘积 6。
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> [-2,0,-1]
<strong>输出:</strong> 0
<strong>解释:</strong>&nbsp;结果不能为 2, 因为 [-2,-1] 不是子数组。</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxProduct(vector<int> &nums)
{
int ans = -10000000;
int n = nums.size();
int max1 = 1, min1 = 1, mx, mn;
for (int i = 0; i < n; i++)
{
mx = max1;
mn = min1;
max1 = max(mx * nums[i], max(nums[i], mn * nums[i]));
min1 = min(mn * nums[i], min(nums[i], mx * nums[i]));
ans = max(max1, ans);
}
return ans;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-d7d3abfcdce548ab912b7845ab999a96",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "5e95ff14e3e34ca8b0c3e643ce327dd3",
"author": "csdn.net",
"keywords": "数组,二分查找",
"notebook_enable": true
}
\ No newline at end of file
# 寻找旋转排序数组中的最小值
已知一个长度为 <code>n</code> 的数组,预先按照升序排列,经由 <code>1</code><code>n</code><strong>旋转</strong> 后,得到输入数组。例如,原数组 <code>nums = [0,1,2,4,5,6,7]</code> 在变化后可能得到:
<ul>
<li>若旋转 <code>4</code> 次,则可以得到 <code>[4,5,6,7,0,1,2]</code></li>
<li>若旋转 <code>7</code> 次,则可以得到 <code>[0,1,2,4,5,6,7]</code></li>
</ul>
<p>注意,数组 <code>[a[0], a[1], a[2], ..., a[n-1]]</code> <strong>旋转一次</strong> 的结果为数组 <code>[a[n-1], a[0], a[1], a[2], ..., a[n-2]]</code></p>
<p>给你一个元素值 <strong>互不相同</strong> 的数组 <code>nums</code> ,它原来是一个升序排列的数组,并按上述情形进行了多次旋转。请你找出并返回数组中的 <strong>最小元素</strong></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>nums = [3,4,5,1,2]
<strong>输出:</strong>1
<strong>解释:</strong>原数组为 [1,2,3,4,5] ,旋转 3 次得到输入数组。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [4,5,6,7,0,1,2]
<strong>输出:</strong>0
<strong>解释:</strong>原数组为 [0,1,2,4,5,6,7] ,旋转 4 次得到输入数组。
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>nums = [11,13,15,17]
<strong>输出:</strong>11
<strong>解释:</strong>原数组为 [11,13,15,17] ,旋转 4 次得到输入数组。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 5000</code></li>
<li><code>-5000 <= nums[i] <= 5000</code></li>
<li><code>nums</code> 中的所有整数 <strong>互不相同</strong></li>
<li><code>nums</code> 原来是一个升序排序的数组,并进行了 <code>1</code><code>n</code> 次旋转</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int findMin(vector<int> &nums)
{
int left = 0, right = nums.size() - 1;
int mid = (left + right) / 2;
while (left < right)
{
mid = (left + right) / 2;
if (nums[mid] > nums[right])
left = mid + 1;
else
right = mid;
}
return nums[left];
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-dd9ab1f390244fc09b52747485de90a5",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "b64fe0d514344234a872ab6ccb13bb92",
"author": "csdn.net",
"keywords": "数组,二分查找",
"notebook_enable": true
}
\ No newline at end of file
# 寻找峰值
<p>峰值元素是指其值严格大于左右相邻值的元素。</p>
<p>给你一个整数数组&nbsp;<code>nums</code>,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回 <strong>任何一个峰值</strong> 所在位置即可。</p>
<p>你可以假设&nbsp;<code>nums[-1] = nums[n] = -∞</code></p>
<p>你必须实现时间复杂度为 <code>O(log n)</code><em> </em>的算法来解决此问题。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>nums = <code>[1,2,3,1]</code>
<strong>输出:</strong>2
<strong>解释:</strong>3 是峰值元素,你的函数应该返回其索引 2。</pre>
<p><strong>示例&nbsp;2:</strong></p>
<pre>
<strong>输入:</strong>nums = <code>[</code>1,2,1,3,5,6,4]
<strong>输出:</strong>1 或 5
<strong>解释:</strong>你的函数可以返回索引 1,其峰值元素为 2;
&nbsp; 或者返回索引 5, 其峰值元素为 6。
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>
<li>对于所有有效的 <code>i</code> 都有 <code>nums[i] != nums[i + 1]</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int findPeakElement(vector<int> &nums)
{
int l = 0, r = nums.size() - 1;
while (l < r)
{
int mid = l + (r - l) / 2;
if (nums[mid] > nums[mid + 1])
{
if (mid == 0 || nums[mid] > nums[mid - 1])
return mid;
else
r = mid;
}
else
{
if (mid + 1 == nums.size() - 1 || nums[mid + 1] > nums[mid + 2])
return mid + 1;
else
l = mid + 1;
}
}
return l;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-5e49fb70f7ba4fa581a2b1e1aa9afeca",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "18a0dcf78cd549869b8437e46fba25bf",
"author": "csdn.net",
"keywords": "双指针,字符串",
"notebook_enable": true
}
\ No newline at end of file
# 比较版本号
<p>给你两个版本号 <code>version1</code><code>version2</code> ,请你比较它们。</p>
<p>版本号由一个或多个修订号组成,各修订号由一个 <code>'.'</code> 连接。每个修订号由 <strong>多位数字</strong> 组成,可能包含 <strong>前导零</strong> 。每个版本号至少包含一个字符。修订号从左到右编号,下标从 0 开始,最左边的修订号下标为 0 ,下一个修订号下标为 1 ,以此类推。例如,<code>2.5.33</code><code>0.1</code> 都是有效的版本号。</p>
<p>比较版本号时,请按从左到右的顺序依次比较它们的修订号。比较修订号时,只需比较 <strong>忽略任何前导零后的整数值</strong> 。也就是说,修订号 <code>1</code> 和修订号 <code>001</code> <strong>相等 </strong>。如果版本号没有指定某个下标处的修订号,则该修订号视为 <code>0</code> 。例如,版本 <code>1.0</code> 小于版本 <code>1.1</code> ,因为它们下标为 <code>0</code> 的修订号相同,而下标为 <code>1</code> 的修订号分别为 <code>0</code><code>1</code><code>0 < 1</code></p>
<p>返回规则如下:</p>
<ul>
<li>如果 <code><em>version1 </em><em>version2</em></code> 返回 <code>1</code></li>
<li>如果 <code><em>version1 </em>< <em>version2</em></code> 返回 <code>-1</code></li>
<li>除此之外返回 <code>0</code></li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>version1 = "1.01", version2 = "1.001"
<strong>输出:</strong>0
<strong>解释:</strong>忽略前导零,"01" 和 "001" 都表示相同的整数 "1"
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>version1 = "1.0", version2 = "1.0.0"
<strong>输出:</strong>0
<strong>解释:</strong>version1 没有指定下标为 2 的修订号,即视为 "0"
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>version1 = "0.1", version2 = "1.1"
<strong>输出:</strong>-1
<strong>解释:</strong>version1 中下标为 0 的修订号是 "0",version2 中下标为 0 的修订号是 "1" 。0 < 1,所以 version1 < version2
</pre>
<p><strong>示例 4:</strong></p>
<pre>
<strong>输入:</strong>version1 = "1.0.1", version2 = "1"
<strong>输出:</strong>1
</pre>
<p><strong>示例 5:</strong></p>
<pre>
<strong>输入:</strong>version1 = "7.5.2.4", version2 = "7.5.3"
<strong>输出:</strong>-1
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= version1.length, version2.length <= 500</code></li>
<li><code>version1</code><code>version2</code> 仅包含数字和 <code>'.'</code></li>
<li><code>version1</code><code>version2</code> 都是 <strong>有效版本号</strong></li>
<li><code>version1</code><code>version2</code> 的所有修订号都可以存储在 <strong>32 位整数</strong></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int compareVersion(string version1, string version2)
{
int val1, val2;
int idx1 = 0, idx2 = 0;
while (idx1 < version1.length() || idx2 < version2.length())
{
val1 = 0;
while (idx1 < version1.length())
{
if (version1[idx1] == '.')
{
++idx1;
break;
}
val1 = val1 * 10 + (version1[idx1] - '0');
idx1++;
}
val2 = 0;
while (idx2 < version2.length())
{
if (version2[idx2] == '.')
{
idx2++;
break;
}
val2 = val2 * 10 + (version2[idx2] - '0');
idx2++;
}
if (val1 > val2)
return 1;
if (val1 < val2)
return -1;
}
return 0;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-fac5c17f457d4cf4b5cf2636c80ffa31",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "1d66b4dc149845938d464a2b38b724f2",
"author": "csdn.net",
"keywords": "哈希表,数学,字符串",
"notebook_enable": true
}
\ No newline at end of file
# 分数到小数
<p>给定两个整数,分别表示分数的分子 <code>numerator</code> 和分母 <code>denominator</code>,以 <strong>字符串形式返回小数</strong></p>
<p>如果小数部分为循环小数,则将循环的部分括在括号内。</p>
<p class="MachineTrans-lang-zh-CN">如果存在多个答案,只需返回 <strong>任意一个</strong></p>
<p class="MachineTrans-lang-zh-CN">对于所有给定的输入,<strong>保证</strong> 答案字符串的长度小于 <code>10<sup>4</sup></code></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>numerator = 1, denominator = 2
<strong>输出:</strong>"0.5"
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>numerator = 2, denominator = 1
<strong>输出:</strong>"2"
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>numerator = 2, denominator = 3
<strong>输出:</strong>"0.(6)"
</pre>
<p><strong>示例 4:</strong></p>
<pre>
<strong>输入:</strong>numerator = 4, denominator = 333
<strong>输出:</strong>"0.(012)"
</pre>
<p><strong>示例 5:</strong></p>
<pre>
<strong>输入:</strong>numerator = 1, denominator = 5
<strong>输出:</strong>"0.2"
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>-2<sup>31</sup> <numerator, denominator <= 2<sup>31</sup> - 1</code></li>
<li><code>denominator != 0</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
string fractionToDecimal(int numerator, int denominator)
{
if (denominator == 0)
return "";
string ans;
if ((numerator > 0 && denominator < 0) || (numerator < 0 && denominator > 0))
ans = "-";
long long num = abs(static_cast<long long>(numerator));
long long den = abs(static_cast<long long>(denominator));
long long quo = num / den;
long long rem = num % den;
ans = ans + to_string(quo);
if (!rem)
return ans;
ans += ".";
unordered_map<long long, int> u_m;
string s = "";
int pos = 0;
while (rem)
{
if (u_m.find(rem) != u_m.end())
{
s.insert(u_m[rem], "(");
s += ")";
return ans + s;
}
u_m[rem] = pos++;
s += to_string((rem * 10) / den);
rem = (rem * 10) % den;
}
return ans + s;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-4a38b31d688641b9843b28b4f373d6e2",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "1de12a0f075f46649a65be099ca6af08",
"author": "csdn.net",
"keywords": "栈,树,设计,二叉搜索树,二叉树,迭代器",
"notebook_enable": true
}
\ No newline at end of file
# 二叉搜索树迭代器
实现一个二叉搜索树迭代器类<code>BSTIterator</code> ,表示一个按中序遍历二叉搜索树(BST)的迭代器:
<div class="original__bRMd">
<div>
<ul>
<li><code>BSTIterator(TreeNode root)</code> 初始化 <code>BSTIterator</code> 类的一个对象。BST 的根节点 <code>root</code> 会作为构造函数的一部分给出。指针应初始化为一个不存在于 BST 中的数字,且该数字小于 BST 中的任何元素。</li>
<li><code>boolean hasNext()</code> 如果向指针右侧遍历存在数字,则返回 <code>true</code> ;否则返回 <code>false</code></li>
<li><code>int next()</code>将指针向右移动,然后返回指针处的数字。</li>
</ul>
<p>注意,指针初始化为一个不存在于 BST 中的数字,所以对 <code>next()</code> 的首次调用将返回 BST 中的最小元素。</p>
</div>
</div>
<p>你可以假设 <code>next()</code> 调用总是有效的,也就是说,当调用 <code>next()</code> 时,BST 的中序遍历中至少存在一个下一个数字。</p>
<p> </p>
<p><strong>示例:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png" style="width: 189px; height: 178px;" />
<pre>
<strong>输入</strong>
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
<strong>输出</strong>
[null, 3, 7, true, 9, true, 15, true, 20, false]
<strong>解释</strong>
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next(); // 返回 3
bSTIterator.next(); // 返回 7
bSTIterator.hasNext(); // 返回 True
bSTIterator.next(); // 返回 9
bSTIterator.hasNext(); // 返回 True
bSTIterator.next(); // 返回 15
bSTIterator.hasNext(); // 返回 True
bSTIterator.next(); // 返回 20
bSTIterator.hasNext(); // 返回 False
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点的数目在范围 <code>[1, 10<sup>5</sup>]</code></li>
<li><code>0 <= Node.val <= 10<sup>6</sup></code></li>
<li>最多调用 <code>10<sup>5</sup></code><code>hasNext</code><code>next</code> 操作</li>
</ul>
<p> </p>
<p><strong>进阶:</strong></p>
<ul>
<li>你可以设计一个满足下述条件的解决方案吗?<code>next()</code><code>hasNext()</code> 操作均摊时间复杂度为 <code>O(1)</code> ,并使用 <code>O(h)</code> 内存。其中 <code>h</code> 是树的高度。</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class BSTIterator
{
public:
BSTIterator(TreeNode *root)
{
for (; root != nullptr; root = root->left)
{
sti_.push(root);
}
}
/** @return the next smallest number */
int next()
{
TreeNode *smallest = sti_.top();
sti_.pop();
int val = smallest->val;
smallest = smallest->right;
for (; smallest != nullptr; smallest = smallest->left)
{
sti_.push(smallest);
}
return val;
}
/** @return whether we have a next smallest number */
bool hasNext()
{
return !sti_.empty();
}
private:
stack<TreeNode *> sti_;
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-734b902304404565abebe151f9f77153",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "6a83c0e417c64208bca61e383ecaa225",
"author": "csdn.net",
"keywords": "贪心,字符串,排序",
"notebook_enable": true
}
\ No newline at end of file
# 最大数
<p>给定一组非负整数 <code>nums</code>,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。</p>
<p><strong>注意:</strong>输出结果可能非常大,所以你需要返回一个字符串而不是整数。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入<code></code></strong><code>nums = [10,2]</code>
<strong>输出:</strong><code>"210"</code></pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入<code></code></strong><code>nums = [3,30,34,5,9]</code>
<strong>输出:</strong><code>"9534330"</code>
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入<code></code></strong>nums = [1]
<strong>输出:</strong>"1"
</pre>
<p><strong>示例 4:</strong></p>
<pre>
<strong>输入<code></code></strong>nums = [10]
<strong>输出:</strong>"10"
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
bool compare(string a, string b)
{
string s1 = a + b;
string s2 = b + a;
return s1 > s2;
}
class Solution
{
public:
string largestNumber(vector<int> &nums)
{
string res = "";
int n = nums.size();
vector<string> tmp;
for (int i = 0; i < n; i++)
{
tmp.push_back(to_string(nums[i]));
}
sort(tmp.begin(), tmp.end(), compare);
for (int i = 0; i < tmp.size(); i++)
{
res += tmp[i];
}
if ('0' == res[0])
{
return "0";
}
else
{
return res;
}
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-6bfbac883a8f424d89c5d4bd00c1166a",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "f2f407f63a6641d8a6a6e98f48b5eb14",
"author": "csdn.net",
"keywords": "位运算,哈希表,字符串,滑动窗口,哈希函数,滚动哈希",
"notebook_enable": true
}
\ No newline at end of file
# 重复的DNA序列
<p>所有 DNA 都由一系列缩写为 <code>'A'</code><code>'C'</code><code>'G'</code><code>'T'</code> 的核苷酸组成,例如:<code>"ACGAATTCCG"</code>。在研究 DNA 时,识别 DNA 中的重复序列有时会对研究非常有帮助。</p>
<p>编写一个函数来找出所有目标子串,目标子串的长度为 10,且在 DNA 字符串 <code>s</code> 中出现次数超过一次。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
<strong>输出:</strong>["AAAAACCCCC","CCCCCAAAAA"]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>s = "AAAAAAAAAAAAA"
<strong>输出:</strong>["AAAAAAAAAA"]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code><code>'A'</code><code>'C'</code><code>'G'</code><code>'T'</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<string> findRepeatedDnaSequences(string s)
{
std::map<std::string, int> word_map;
std::vector<std::string> result;
for (int i = 0; i < s.length(); i++)
{
std::string word = s.substr(i, 10);
if (word_map.find(word) != word_map.end())
{
word_map[word] += 1;
}
else
{
word_map[word] = 1;
}
}
std::map<std::string, int>::iterator it;
for (it = word_map.begin(); it != word_map.end(); it++)
{
if (it->second > 1)
{
result.push_back(it->first);
}
}
return result;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-617ecf41c10541368e4d2585d3a5f77c",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "e5f17936775e4f7fb4aee5b522a5153e",
"author": "csdn.net",
"keywords": "数组,数学,双指针",
"notebook_enable": true
}
\ No newline at end of file
# 旋转数组
<p>给定一个数组,将数组中的元素向右移动 <code>k</code><em> </em>个位置,其中 <code>k</code><em> </em>是非负数。</p>
<p> </p>
<p><strong>进阶:</strong></p>
<ul>
<li>尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。</li>
<li>你可以使用空间复杂度为 O(1) 的 <strong>原地 </strong>算法解决这个问题吗?</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> nums = [1,2,3,4,5,6,7], k = 3
<strong>输出:</strong> <code>[5,6,7,1,2,3,4]</code>
<strong>解释:</strong>
向右旋转 1 步: <code>[7,1,2,3,4,5,6]</code>
向右旋转 2 步: <code>[6,7,1,2,3,4,5]
</code>向右旋转 3 步: <code>[5,6,7,1,2,3,4]</code>
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [-1,-100,3,99], k = 2
<strong>输出:</strong>[3,99,-1,-100]
<strong>解释:</strong>
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
</ul>
<ul>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
void rotate(vector<int> &nums, int k)
{
if (nums.empty())
{
return;
}
int length = nums.size();
k %= length;
while (k--)
{
int temp = nums[length - 1];
for (int i = length - 1; i > 0; i--)
{
nums[i] = nums[i - 1];
}
nums[0] = temp;
}
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-a4304e9fcd084439be358b1e58347100",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "91c2d236f2624016849c993a4c798f98",
"author": "csdn.net",
"keywords": "数组,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 打家劫舍
<p>你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,<strong>如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警</strong></p>
<p>给定一个代表每个房屋存放金额的非负整数数组,计算你<strong> 不触动警报装置的情况下 </strong>,一夜之内能够偷窃到的最高金额。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>[1,2,3,1]
<strong>输出:</strong>4
<strong>解释:</strong>偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
  偷窃到的最高金额 = 1 + 3 = 4 。</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>[2,7,9,3,1]
<strong>输出:</strong>12
<strong>解释:</strong>偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
  偷窃到的最高金额 = 2 + 9 + 1 = 12 。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 400</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int rob(vector<int> &nums)
{
int n = nums.size();
if (n == 0)
{
return 0;
}
vector<long> f(n + 1);
f[1] = nums[0];
for (int i = 2; i <= n; ++i)
{
f[i] = max(f[i - 1], f[i - 2] + nums[i - 1]);
}
return f[n];
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-96ae9dfe598347d1ab79aa2750046db6",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "fde5bfc5ffcc4372b5b173f3f8128454",
"author": "csdn.net",
"keywords": "树,深度优先搜索,广度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 二叉树的右视图
<p>给定一个二叉树的 <strong>根节点</strong> <code>root</code>,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<p><img src="https://assets.leetcode.com/uploads/2021/02/14/tree.jpg" style="width: 270px; " /></p>
<pre>
<strong>输入:</strong> [1,2,3,null,5,null,4]
<strong>输出:</strong> [1,3,4]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> [1,null,3]
<strong>输出:</strong> [1,3]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong> []
<strong>输出:</strong> []
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>二叉树的节点个数的范围是 <code>[0,100]</code></li>
<li><meta charset="UTF-8" /><code>-100 <= Node.val <= 100</code> </li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<int> rightSideView(TreeNode *root)
{
vector<int> ret;
queue<TreeNode *> queues[2];
if (root != NULL)
queues[0].push(root);
int i = 0, j = 1, tmp;
TreeNode *p;
while (!queues[0].empty() || !queues[1].empty())
{
while (!queues[i].empty())
{
p = queues[i].front();
queues[i].pop();
if (p->left)
queues[j].push(p->left);
if (p->right)
queues[j].push(p->right);
tmp = p->val;
}
ret.push_back(tmp);
i = (i + 1) % 2;
j = (j + 1) % 2;
}
return ret;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-b42a7f99c1f84575bed9b796d6c8bf85",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "15ff375cf08d4b87b030c8b39867567d",
"author": "csdn.net",
"keywords": "深度优先搜索,广度优先搜索,并查集,数组,矩阵",
"notebook_enable": true
}
\ No newline at end of file
# 岛屿数量
<p>给你一个由 <code>'1'</code>(陆地)和 <code>'0'</code>(水)组成的的二维网格,请你计算网格中岛屿的数量。</p>
<p>岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。</p>
<p>此外,你可以假设该网格的四条边均被水包围。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
<strong>输出:</strong>1
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
<strong>输出:</strong>3
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 300</code></li>
<li><code>grid[i][j]</code> 的值为 <code>'0'</code><code>'1'</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
void DFS(vector<vector<int>> &mark, vector<vector<char>> &grid, int x, int y)
{
mark[x][y] = 1;
static const int dx[] = {-1, 1, 0, 0};
static const int dy[] = {0, 0, -1, 1};
for (int i = 0; i < 4; i++)
{
int newx = dx[i] + x;
int newy = dy[i] + y;
if (newx < 0 || newx >= mark.size() || newy < 0 || newy >= mark[newx].size())
{
continue;
}
if (mark[newx][newy] == 0 && grid[newx][newy] == '1')
{
DFS(mark, grid, newx, newy);
}
}
}
int numIslands(vector<vector<char>> &grid)
{
int island_num = 0;
vector<vector<int>> mark;
for (int i = 0; i < grid.size(); i++)
{
mark.push_back(vector<int>());
for (int j = 0; j < grid[i].size(); j++)
{
mark[i].push_back(0);
}
}
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[i].size(); j++)
{
if (mark[i][j] == 0 && grid[i][j] == '1')
{
DFS(mark, grid, i, j);
island_num++;
}
}
}
return island_num;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-74b08309f19b41869c4320ea58482f6c",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "0efe4da13111471eaabaf79555034398",
"author": "csdn.net",
"keywords": "树,广度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 二叉树的层序遍历
<p>给你一个二叉树,请你返回其按 <strong>层序遍历</strong> 得到的节点值。 (即逐层地,从左到右访问所有节点)。</p>
<p> </p>
<p><strong>示例:</strong><br />
二叉树:<code>[3,9,20,null,null,15,7]</code>,</p>
<pre>
3
/ \
9 20
/ \
15 7
</pre>
<p>返回其层序遍历结果:</p>
<pre>
[
[3],
[9,20],
[15,7]
]
</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int>> levelOrder(TreeNode *root)
{
if (root == NULL)
return {};
queue<TreeNode *> queue;
TreeNode *p = root;
vector<vector<int>> res;
queue.push(p);
while (queue.empty() == false)
{
vector<int> temp = {};
int length = queue.size();
for (int i = 0; i < length; i++)
{
p = queue.front();
queue.pop();
temp.push_back(p->val);
if (p->left)
queue.push(p->left);
if (p->right)
queue.push(p->right);
}
res.push_back(temp);
}
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-60c41833285047f3b321443845611bce",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "b9f1269194384877b4442ca8e7abf180",
"author": "csdn.net",
"keywords": "树,广度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 二叉树的锯齿形层序遍历
<p>给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。</p>
<p>例如:<br />
给定二叉树 <code>[3,9,20,null,null,15,7]</code>,</p>
<pre>
3
/ \
9 20
/ \
15 7
</pre>
<p>返回锯齿形层序遍历如下:</p>
<pre>
[
[3],
[20,9],
[15,7]
]
</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int>> zigzagLevelOrder(TreeNode *root)
{
if (!root)
return {};
vector<vector<int>> res;
vector<int> temp;
int level = 0;
queue<pair<TreeNode *, int>> q;
q.push(pair(root, 0));
while (!q.empty())
{
TreeNode *node = q.front().first;
level = q.front().second;
q.pop();
if (res.size() < level)
{
if (level % 2 == 0)
reverse(temp.begin(), temp.end());
res.push_back(temp);
temp.clear();
}
temp.push_back(node->val);
if (node->left)
q.push(pair(node->left, level + 1));
if (node->right)
q.push(pair(node->right, level + 1));
}
if (level % 2 != 0)
reverse(temp.begin(), temp.end());
res.push_back(temp);
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-dff4c4e10e6f42a1ac201dd4d0ff8664",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "ba75cf15fbae4173ae855d7975a09c08",
"author": "csdn.net",
"keywords": "树,数组,哈希表,分治,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 从前序与中序遍历序列构造二叉树
<p>给定一棵树的前序遍历 <code>preorder</code> 与中序遍历  <code>inorder</code>。请构造二叉树并返回其根节点。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" />
<pre>
<strong>Input:</strong> preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
<strong>Output:</strong> [3,9,20,null,null,15,7]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>Input:</strong> preorder = [-1], inorder = [-1]
<strong>Output:</strong> [-1]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= preorder.length <= 3000</code></li>
<li><code>inorder.length == preorder.length</code></li>
<li><code>-3000 <= preorder[i], inorder[i] <= 3000</code></li>
<li><code>preorder</code> 和 <code>inorder</code> 均无重复元素</li>
<li><code>inorder</code> 均出现在 <code>preorder</code></li>
<li><code>preorder</code> 保证为二叉树的前序遍历序列</li>
<li><code>inorder</code> 保证为二叉树的中序遍历序列</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
private:
unordered_map<int, int> inMap;
public:
TreeNode *myBuildTree(vector<int> &preorder, int preStart, int preEnd, vector<int> &inorder, int inStart, int inEnd)
{
if (preStart > preEnd)
return nullptr;
TreeNode *root = new TreeNode(preorder[preStart]);
int inRoot = inMap[preorder[preStart]];
int numsLeft = inRoot - inStart;
root->left = myBuildTree(preorder, preStart + 1, preStart + numsLeft, inorder, inStart, inRoot - 1);
root->right = myBuildTree(preorder, preStart + numsLeft + 1, preEnd, inorder, inRoot + 1, inEnd);
return root;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder)
{
int n = preorder.size();
for (int i = 0; i < n; i++)
{
inMap[inorder[i]] = i;
}
return myBuildTree(preorder, 0, n - 1, inorder, 0, n - 1);
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-b8f6aa5c87444972987d7e7a1e52a22c",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "114fd3f88e654e509ae581d5b5283b34",
"author": "csdn.net",
"keywords": "树,数组,哈希表,分治,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 从中序与后序遍历序列构造二叉树
<p>根据一棵树的中序遍历与后序遍历构造二叉树。</p>
<p><strong>注意:</strong><br>
你可以假设树中没有重复的元素。</p>
<p>例如,给出</p>
<pre>中序遍历 inorder =&nbsp;[9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]</pre>
<p>返回如下的二叉树:</p>
<pre> 3
/ \
9 20
/ \
15 7
</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
{
if (0 == inorder.size() || 0 == postorder.size())
{
return NULL;
}
return build(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
}
TreeNode *build(vector<int> &inorder, int i1, int i2, vector<int> &postorder, int p1, int p2)
{
TreeNode *root = new TreeNode(postorder[p2]);
int i = i1;
while (i <= i2 && postorder[p2] != inorder[i])
{
i++;
}
int left = i - i1;
int right = i2 - i;
if (left > 0)
{
root->left = build(inorder, i1, i - 1, postorder, p1, p1 + left - 1);
}
if (right > 0)
{
root->right = build(inorder, i + 1, i2, postorder, p1 + left, p2 - 1);
}
return root;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-d26621ba92b24aeeb003c86d47d36ad6",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "3d8e9a5ee3b6439d92b567b667c50864",
"author": "csdn.net",
"keywords": "树,广度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 二叉树的层序遍历 II
<p>给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)</p>
<p>例如:<br />
给定二叉树 <code>[3,9,20,null,null,15,7]</code>,</p>
<pre>
3
/ \
9 20
/ \
15 7
</pre>
<p>返回其自底向上的层序遍历为:</p>
<pre>
[
[15,7],
[9,20],
[3]
]
</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int>> levelOrderBottom(TreeNode *root)
{
vector<vector<int>> res;
if (root == NULL)
return res;
queue<TreeNode *> q;
q.push(root);
while (!q.empty())
{
vector<int> oneLevel;
int size = q.size();
for (int i = 0; i < size; i++)
{
TreeNode *node = q.front();
q.pop();
oneLevel.push_back(node->val);
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
}
res.insert(res.begin(), oneLevel);
}
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-935af29ed8e5492cbb0712c8b1d0c653",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "8532653591304c138feba57d32124c1c",
"author": "csdn.net",
"keywords": "树,二叉搜索树,链表,分治,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 有序链表转换二叉搜索树
<p>给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。</p>
<p>本题中,一个高度平衡二叉树是指一个二叉树<em>每个节点&nbsp;</em>的左右两个子树的高度差的绝对值不超过 1。</p>
<p><strong>示例:</strong></p>
<pre>给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
vector<int> nums;
TreeNode *create(int low, int high)
{
if (low > high)
return NULL;
int mid = (low + high) / 2;
auto root = new TreeNode(nums[mid]);
root->left = create(low, mid - 1);
root->right = create(mid + 1, high);
return root;
}
TreeNode *sortedListToBST(ListNode *head)
{
while (head)
{
nums.push_back(head->val);
head = head->next;
}
return create(0, nums.size() - 1);
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-d202c192ccde42a8a79bb7439fc7bf10",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "f891f16e32ea433e9dc188d9ea0d65ee",
"author": "csdn.net",
"keywords": "树,深度优先搜索,回溯,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 路径总和 II
<p>给你二叉树的根节点 <code>root</code> 和一个整数目标和 <code>targetSum</code> ,找出所有 <strong>从根节点到叶子节点</strong> 路径总和等于给定目标和的路径。</p>
<p><strong>叶子节点</strong> 是指没有子节点的节点。</p>
<div class="original__bRMd">
<div>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg" style="width: 500px; height: 356px;" />
<pre>
<strong>输入:</strong>root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
<strong>输出:</strong>[[5,4,11,2],[5,8,4,5]]
</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" style="width: 212px; height: 181px;" />
<pre>
<strong>输入:</strong>root = [1,2,3], targetSum = 5
<strong>输出:</strong>[]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>root = [1,2], targetSum = 0
<strong>输出:</strong>[]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点总数在范围 <code>[0, 5000]</code></li>
<li><code>-1000 <= Node.val <= 1000</code></li>
<li><code>-1000 <= targetSum <= 1000</code></li>
</ul>
</div>
</div>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int>> pathSum(TreeNode *root, int sum)
{
vector<vector<int>> res;
vector<int> track;
backTrack(root, res, track, sum);
return res;
}
void backTrack(TreeNode *root, vector<vector<int>> &res, vector<int> track, int sum)
{
if (!root)
{
return;
}
if (!root->left && !root->right)
{
sum -= root->val;
track.push_back(root->val);
if (sum == 0)
{
res.push_back(track);
}
track.pop_back();
sum += root->val;
return;
}
sum -= root->val;
track.push_back(root->val);
backTrack(root->left, res, track, sum);
backTrack(root->right, res, track, sum);
track.pop_back();
sum += root->val;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-2728da0a5a584b3b8eee17473182c2e2",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "fd0fc75e932545d8ba6c3ecc71bebf22",
"author": "csdn.net",
"keywords": "栈,树,深度优先搜索,链表,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 二叉树展开为链表
<p>给你二叉树的根结点 <code>root</code> ,请你将它展开为一个单链表:</p>
<ul>
<li>展开后的单链表应该同样使用 <code>TreeNode</code> ,其中 <code>right</code> 子指针指向链表中下一个结点,而左子指针始终为 <code>null</code></li>
<li>展开后的单链表应该与二叉树 <a href="https://baike.baidu.com/item/%E5%85%88%E5%BA%8F%E9%81%8D%E5%8E%86/6442839?fr=aladdin" target="_blank"><strong>先序遍历</strong></a> 顺序相同。</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg" style="width: 500px; height: 226px;" />
<pre>
<strong>输入:</strong>root = [1,2,5,3,4,null,6]
<strong>输出:</strong>[1,null,2,null,3,null,4,null,5,null,6]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>root = []
<strong>输出:</strong>[]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>root = [0]
<strong>输出:</strong>[0]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中结点数在范围 <code>[0, 2000]</code></li>
<li><code>-100 <= Node.val <= 100</code></li>
</ul>
<p> </p>
<p><strong>进阶:</strong>你可以使用原地算法(<code>O(1)</code> 额外空间)展开这棵树吗?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
void rconnect(TreeNode *&node, TreeNode *pmove)
{
if (pmove == nullptr)
return;
node->right = new TreeNode(pmove->val);
node->left = nullptr;
node = node->right;
rconnect(node, pmove->left);
rconnect(node, pmove->right);
}
void flatten(TreeNode *root)
{
if (root == nullptr)
return;
TreeNode *head = new TreeNode();
TreeNode *newroot = head;
rconnect(head, root);
newroot = newroot->right->right;
root->right = newroot;
root->left = nullptr;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-4e7bac103be94ad1b0b11a1ee6256987",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "8a772d0bda8142c3bdddb1b4d18cc62a",
"author": "csdn.net",
"keywords": "树,深度优先搜索,广度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 填充每个节点的下一个右侧节点指针
<p>给定一个 <strong>完美二叉树 </strong>,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:</p>
<pre>
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}</pre>
<p>填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 <code>NULL</code></p>
<p>初始状态下,所有 next 指针都被设置为 <code>NULL</code></p>
<p> </p>
<p><strong>进阶:</strong></p>
<ul>
<li>你只能使用常量级额外空间。</li>
<li>使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。</li>
</ul>
<p> </p>
<p><strong>示例:</strong></p>
<p><img alt="" src="https://assets.leetcode.com/uploads/2019/02/14/116_sample.png" style="height: 205px; width: 600px;" /></p>
<pre>
<b>输入:</b>root = [1,2,3,4,5,6,7]
<b>输出:</b>[1,#,2,3,#,4,5,6,7,#]
<b>解释:</b>给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化的输出按层序遍历排列,同一层节点由 next 指针连接,'#' 标志着每一层的结束。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点的数量少于 <code>4096</code></li>
<li><code>-1000 <= node.val <= 1000</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node *left;
Node *right;
Node *next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node *_left, Node *_right, Node *_next)
: val(_val), left(_left), right(_right), next(_next) {}
};
class Solution
{
public:
Node *connect(Node *root)
{
if (!root)
return nullptr;
root->next = nullptr;
connect_helper(root);
return root;
}
private:
void connect_helper(Node *pNode)
{
if (!pNode)
return;
if (pNode->left == nullptr)
return;
pNode->left->next = pNode->right;
if (pNode->right == nullptr)
return;
if (pNode->next != nullptr)
pNode->right->next = pNode->next->left;
else
pNode->right->next = nullptr;
connect_helper(pNode->left);
connect_helper(pNode->right);
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-acbff7e537ff4e00aafefb58ac6f1bd8",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "fd74d5ca92e349568bf63c4e9ebdeed9",
"author": "csdn.net",
"keywords": "树,深度优先搜索,广度优先搜索,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 填充每个节点的下一个右侧节点指针 II
<p>给定一个二叉树</p>
<pre>
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}</pre>
<p>填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 <code>NULL</code></p>
<p>初始状态下,所有 next 指针都被设置为 <code>NULL</code></p>
<p> </p>
<p><strong>进阶:</strong></p>
<ul>
<li>你只能使用常量级额外空间。</li>
<li>使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。</li>
</ul>
<p> </p>
<p><strong>示例:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/15/117_sample.png" style="height: 218px; width: 640px;" /></p>
<pre>
<strong>输入</strong>:root = [1,2,3,4,5,null,7]
<strong>输出:</strong>[1,#,2,3,#,4,5,7,#]
<strong>解释:</strong>给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化输出按层序遍历顺序(由 next 指针连接),'#' 表示每层的末尾。</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中的节点数小于 <code>6000</code></li>
<li><code>-100 <= node.val <= 100</code></li>
</ul>
<p> </p>
<ul>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node *left;
Node *right;
Node *next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node *_left, Node *_right, Node *_next)
: val(_val), left(_left), right(_right), next(_next) {}
};
class Solution
{
public:
Node *connect(Node *root)
{
if (!root)
return NULL;
Node *p = root->next;
while (p)
{
if (p->left)
{
p = p->left;
break;
}
if (p->right)
{
p = p->right;
break;
}
p = p->next;
}
if (root->right)
root->right->next = p;
if (root->left)
root->left->next = root->right ? root->right : p;
connect(root->right);
connect(root->left);
return root;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-b84e0ad3b5c8484ab8dbb922eeead085",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "383ae4c542d449439fc15dd853dbf9cd",
"author": "csdn.net",
"keywords": "数组,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 三角形最小路径和
<p>给定一个三角形 <code>triangle</code> ,找出自顶向下的最小路径和。</p>
<p>每一步只能移动到下一行中相邻的结点上。<strong>相邻的结点 </strong>在这里指的是 <strong>下标</strong><strong>上一层结点下标</strong> 相同或者等于 <strong>上一层结点下标 + 1</strong> 的两个结点。也就是说,如果正位于当前行的下标 <code>i</code> ,那么下一步可以移动到下一行的下标 <code>i</code><code>i + 1</code></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
<strong>输出:</strong>11
<strong>解释:</strong>如下面简图所示:
<strong>2</strong>
<strong>3</strong> 4
6 <strong>5</strong> 7
4 <strong>1</strong> 8 3
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>triangle = [[-10]]
<strong>输出:</strong>-10
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= triangle.length <= 200</code></li>
<li><code>triangle[0].length == 1</code></li>
<li><code>triangle[i].length == triangle[i - 1].length + 1</code></li>
<li><code>-10<sup>4</sup> <= triangle[i][j] <= 10<sup>4</sup></code></li>
</ul>
<p> </p>
<p><strong>进阶:</strong></p>
<ul>
<li>你可以只使用 <code>O(n)</code> 的额外空间(<code>n</code> 为三角形的总行数)来解决这个问题吗?</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int minimumTotal(vector<vector<int>> &triangle)
{
int n = triangle.size();
if (n == 0)
return 0;
if (n == 1)
return triangle[0][0];
vector<vector<int>> info(n, vector<int>(n, 0));
info[0][0] = triangle[0][0];
for (int i = 1; i < n; ++i)
{
for (int j = 0; j <= i; ++j)
{
if (j == 0)
info[i][j] = triangle[i][j] + info[i - 1][j];
else if (j == i)
info[i][j] = triangle[i][j] + info[i - 1][j - 1];
else
{
int temp = info[i - 1][j] > info[i - 1][j - 1] ? info[i - 1][j - 1] : info[i - 1][j];
info[i][j] = temp + triangle[i][j];
}
}
}
int res = info[n - 1][0];
for (int i = 0; i < n; ++i)
{
if (info[n - 1][i] < res)
{
res = info[n - 1][i];
}
}
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-abe1e612615b4a0cb30c4d43d8317bcf",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "51ccf4e117df4625be67d2c9ff6bab72",
"author": "csdn.net",
"keywords": "并查集,数组,哈希表",
"notebook_enable": true
}
\ No newline at end of file
# 最长连续序列
<p>给定一个未排序的整数数组 <code>nums</code> ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。</p>
<p>请你设计并实现时间复杂度为 <code>O(n)</code><em> </em>的算法解决此问题。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>nums = [100,4,200,1,3,2]
<strong>输出:</strong>4
<strong>解释:</strong>最长数字连续序列是 <code>[1, 2, 3, 4]。它的长度为 4。</code></pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [0,3,7,2,5,8,4,6,0,1]
<strong>输出:</strong>9
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int longestConsecutive(vector<int> &nums)
{
unordered_set<int> s;
for (auto v : nums)
s.insert(v);
int res = 0;
for (auto v : nums)
{
if (s.find(v) != s.end())
{
s.erase(v);
int temp = 1;
int cur = v;
while (s.find(cur - 1) != s.end())
{
cur--;
s.erase(cur);
}
temp += v - cur;
cur = v;
while (s.find(cur + 1) != s.end())
{
cur++;
s.erase(cur);
}
temp += cur - v;
res = max(res, temp);
}
}
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-20b092dea834439fb605c1749d6e268b",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "4175e229f9cb4ec297b994f018f5bf95",
"author": "csdn.net",
"keywords": "字符串,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 不同的子序列
<p>给定一个字符串 <code>s</code><strong> </strong>和一个字符串 <code>t</code> ,计算在 <code>s</code> 的子序列中 <code>t</code> 出现的个数。</p>
<p>字符串的一个 <strong>子序列</strong> 是指,通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串。(例如,<code>"ACE"</code> 是 <code>"ABCDE"</code> 的一个子序列,而 <code>"AEC"</code> 不是)</p>
<p>题目数据保证答案符合 32 位带符号整数范围。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>s = "rabbbit", t = "rabbit"<code>
<strong>输出</strong></code><strong></strong><code>3
</code><strong>解释:</strong>
如下图所示, 有 3 种可以从 s 中得到 <code>"rabbit" 的方案</code>
<code><strong><u>rabb</u></strong>b<strong><u>it</u></strong></code>
<code><strong><u>ra</u></strong>b<strong><u>bbit</u></strong></code>
<code><strong><u>rab</u></strong>b<strong><u>bit</u></strong></code></pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>s = "babgbag", t = "bag"
<code><strong>输出</strong></code><strong></strong><code>5
</code><strong>解释:</strong>
如下图所示, 有 5 种可以从 s 中得到 <code>"bag" 的方案</code>
<code><strong><u>ba</u></strong>b<u><strong>g</strong></u>bag</code>
<code><strong><u>ba</u></strong>bgba<strong><u>g</u></strong></code>
<code><u><strong>b</strong></u>abgb<strong><u>ag</u></strong></code>
<code>ba<u><strong>b</strong></u>gb<u><strong>ag</strong></u></code>
<code>babg<strong><u>bag</u></strong></code>
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 <= s.length, t.length <= 1000</code></li>
<li><code>s</code><code>t</code> 由英文字母组成</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int numDistinct(string s, string t)
{
long dp[t.size() + 1][s.size() + 1];
for (int i = 0; i <= s.size(); ++i)
dp[0][i] = 1;
for (int i = 1; i <= t.size(); ++i)
dp[i][0] = 0;
for (int i = 1; i <= t.size(); ++i)
{
for (int j = 1; j <= s.size(); ++j)
{
dp[i][j] = dp[i][j - 1] + (t[i - 1] == s[j - 1] ? dp[i - 1][j - 1] : 0);
}
}
return dp[t.size()][s.size()];
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-b21a1bcfe07c466d894abf1624a2e27b",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "14750c7919bf4d9cb1cc1b9dc589acd9",
"author": "csdn.net",
"keywords": "数组,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 买卖股票的最佳时机 III
<p>给定一个数组,它的第<em> </em><code>i</code> 个元素是一支给定的股票在第 <code>i</code><em> </em>天的价格。</p>
<p>设计一个算法来计算你所能获取的最大利润。你最多可以完成 <strong>两笔 </strong>交易。</p>
<p><strong>注意:</strong>你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>prices = [3,3,5,0,0,3,1,4]
<strong>输出:</strong>6
<strong>解释:</strong>在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。
  随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>prices = [1,2,3,4,5]
<strong>输出:</strong>4
<strong>解释:</strong>在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。  
  注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。  
  因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>prices = [7,6,4,3,1]
<strong>输出:</strong>0
<strong>解释:</strong>在这个情况下, 没有交易完成, 所以最大利润为 0。</pre>
<p><strong>示例 4:</strong></p>
<pre>
<strong>输入:</strong>prices = [1]
<strong>输出:</strong>0
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <prices.length <= 10<sup>5</sup></code></li>
<li><code>0 <prices[i] <= 10<sup>5</sup></code></li>
</ul>
## template
```cpp
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
int length = prices.size();
if (length < 2)
{
return 0;
}
vector<int> former(length, 0);
vector<int> later(length, 0);
int curMin = prices[0];
int curProfit = 0;
for (int i = 1; i < length; i++)
{
curProfit = max(curProfit, prices[i] - curMin);
curMin = min(curMin, prices[i]);
former[i] = curProfit;
}
int curMax = prices[length - 1];
curProfit = 0;
for (int i = length - 2; i >= 0; i--)
{
curProfit = max(curProfit, curMax - prices[i]);
curMax = max(curMax, prices[i]);
later[i] = curProfit;
}
int maxProfit = 0;
for (int i = 0; i < length; i++)
maxProfit = max(maxProfit, former[i] + later[i]);
return maxProfit;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-d58de695f661474f8a2f72bf151c32f4",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "9cb85eede3984b70b08147e8b4525294",
"author": "csdn.net",
"keywords": "树,深度优先搜索,动态规划,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 二叉树中的最大路径和
<p><strong>路径</strong> 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 <strong>至多出现一次</strong> 。该路径<strong> 至少包含一个 </strong>节点,且不一定经过根节点。</p>
<p><strong>路径和</strong> 是路径中各节点值的总和。</p>
<p>给你一个二叉树的根节点 <code>root</code> ,返回其 <strong>最大路径和</strong></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg" style="width: 322px; height: 182px;" />
<pre>
<strong>输入:</strong>root = [1,2,3]
<strong>输出:</strong>6
<strong>解释:</strong>最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg" />
<pre>
<strong>输入:</strong>root = [-10,9,20,null,null,15,7]
<strong>输出:</strong>42
<strong>解释:</strong>最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点数目范围是 <code>[1, 3 * 10<sup>4</sup>]</code></li>
<li><code>-1000 <= Node.val <= 1000</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int maxPathSum(TreeNode *root)
{
if (!root)
return 0;
vector<TreeNode *> ss;
unordered_map<TreeNode *, int> val;
ss.push_back(root);
int len = 1;
queue<TreeNode *> q{{root}};
while (!q.empty())
{
TreeNode *t = q.front();
q.pop();
cout << t->val << endl;
if (t->left)
{
len++;
q.push(t->left);
ss.push_back(t->left);
}
if (t->right)
{
len++;
q.push(t->right);
ss.push_back(t->right);
}
}
int res = INT_MIN;
while (len > 0)
{
TreeNode *node = ss[--len];
int ps = node->val;
int s = ps;
int ls = max(0, val[node->left]);
int rs = max(0, val[node->right]);
ps += max(ls, rs);
val[node] = ps;
s += ls + rs;
res = max(s, res);
}
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-d92de43caa3540a4b5aa693d35035468",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "bc43d567d92b494b84197834566161dd",
"author": "csdn.net",
"keywords": "广度优先搜索,哈希表,字符串,回溯",
"notebook_enable": true
}
\ No newline at end of file
# 单词接龙 II
<p>按字典 <code>wordList</code> 完成从单词 <code>beginWord</code> 到单词 <code>endWord</code> 转化,一个表示此过程的 <strong>转换序列</strong> 是形式上像 <code>beginWord -> s<sub>1</sub> -> s<sub>2</sub> -> ... -> s<sub>k</sub></code> 这样的单词序列,并满足:</p>
<div class="original__bRMd">
<div>
<ul>
<li>每对相邻的单词之间仅有单个字母不同。</li>
<li>转换过程中的每个单词 <code>s<sub>i</sub></code><code>1 <= i <= k</code>)必须是字典 <code>wordList</code> 中的单词。注意,<code>beginWord</code> 不必是字典 <code>wordList</code> 中的单词。</li>
<li><code>s<sub>k</sub> == endWord</code></li>
</ul>
<p>给你两个单词 <code>beginWord</code><code>endWord</code> ,以及一个字典 <code>wordList</code> 。请你找出并返回所有从 <code>beginWord</code><code>endWord</code><strong>最短转换序列</strong> ,如果不存在这样的转换序列,返回一个空列表。每个序列都应该以单词列表<em> </em><code>[beginWord, s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub>]</code> 的形式返回。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
<strong>输出:</strong>[["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
<strong>解释:</strong>存在 2 种最短的转换序列:
"hit" -> "hot" -> "dot" -> "dog" -> "cog"
"hit" -> "hot" -> "lot" -> "log" -> "cog"
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
<strong>输出:</strong>[]
<strong>解释:</strong>endWord "cog" 不在字典 wordList 中,所以不存在符合要求的转换序列。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= beginWord.length <= 7</code></li>
<li><code>endWord.length == beginWord.length</code></li>
<li><code>1 <= wordList.length <= 5000</code></li>
<li><code>wordList[i].length == beginWord.length</code></li>
<li><code>beginWord</code><code>endWord</code><code>wordList[i]</code> 由小写英文字母组成</li>
<li><code>beginWord != endWord</code></li>
<li><code>wordList</code> 中的所有单词 <strong>互不相同</strong></li>
</ul>
</div>
</div>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool differ_one(string &s, string &t)
{
int n = 0;
for (int i = 0; i < s.size(); ++i)
if ((n += s[i] != t[i]) > 1)
return false;
return n == 1;
}
vector<vector<int>> fa;
vector<string> tmp;
vector<vector<string>> ans;
void dfs(int index, vector<string> &wordList)
{
if (fa[index].empty())
{
reverse(tmp.begin(), tmp.end());
ans.push_back(tmp);
reverse(tmp.begin(), tmp.end());
}
for (auto &x : fa[index])
{
tmp.push_back(wordList[x]);
dfs(x, wordList);
tmp.pop_back();
}
}
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string> &wordList)
{
int b = -1, e = -1, x;
for (int i = 0; i < wordList.size(); ++i)
{
if (wordList[i] == beginWord)
b = i;
if (wordList[i] == endWord)
e = i;
}
if (e == -1)
return ans;
if (b == -1)
wordList.push_back(beginWord), b = wordList.size() - 1;
queue<int> que;
fa.assign(wordList.size(), vector<int>());
vector<int> index(wordList.size(), 0);
que.push(b), index[b] = 1;
while (!que.empty())
{
x = que.front(), que.pop();
if (index[e] && index[x] >= index[e])
break;
for (int i = 0; i < wordList.size(); ++i)
if ((index[i] == 0 || index[x] + 1 == index[i]) && differ_one(wordList[x], wordList[i]))
if (index[i] == 0)
index[i] = index[x] + 1, que.push(i), fa[i].push_back(x);
else
fa[i].push_back(x);
}
if (index[e] == 0)
return ans;
tmp.push_back(endWord);
dfs(e, wordList);
tmp.pop_back();
return ans;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-98daf8a40cf94f16b451b22387358559",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "d8fd443f1d594cca97e0cbba610a3249",
"author": "csdn.net",
"keywords": "广度优先搜索,哈希表,字符串",
"notebook_enable": true
}
\ No newline at end of file
# 单词接龙
<p>字典 <code>wordList</code> 中从单词 <code>beginWord</code><em> </em><code>endWord</code><strong>转换序列 </strong>是一个按下述规格形成的序列:</p>
<ul>
<li>序列中第一个单词是 <code>beginWord</code></li>
<li>序列中最后一个单词是 <code>endWord</code></li>
<li>每次转换只能改变一个字母。</li>
<li>转换过程中的中间单词必须是字典 <code>wordList</code> 中的单词。</li>
</ul>
<p>给你两个单词<em> </em><code>beginWord</code><em> </em><code>endWord</code> 和一个字典 <code>wordList</code> ,找到从 <code>beginWord</code> 到 <code>endWord</code><strong>最短转换序列</strong> 中的 <strong>单词数目</strong> 。如果不存在这样的转换序列,返回 0。</p>
 
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
<strong>输出:</strong>5
<strong>解释:</strong>一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog", 返回它的长度 5。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
<strong>输出:</strong>0
<strong>解释:</strong>endWord "cog" 不在字典中,所以无法进行转换。</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= beginWord.length <= 10</code></li>
<li><code>endWord.length == beginWord.length</code></li>
<li><code>1 <= wordList.length <= 5000</code></li>
<li><code>wordList[i].length == beginWord.length</code></li>
<li><code>beginWord</code><code>endWord</code><code>wordList[i]</code> 由小写英文字母组成</li>
<li><code>beginWord != endWord</code></li>
<li><code>wordList</code> 中的所有字符串 <strong>互不相同</strong></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int ladderLength(string beginWord, string endWord, vector<string> &wordList)
{
unordered_set<string> dict(wordList.begin(), wordList.end());
if (dict.find(endWord) == dict.end())
return 0;
queue<pair<string, int>> q;
q.push(make_pair(beginWord, 1));
string tmp;
int step;
while (!q.empty())
{
auto p = q.front();
if (p.first == endWord)
return p.second;
tmp = p.first;
step = p.second;
q.pop();
char old_ch;
for (int i = 0; i < tmp.size(); ++i)
{
old_ch = tmp[i];
for (char c = 'a'; c <= 'z'; ++c)
{
if (c == old_ch)
continue;
tmp[i] = c;
if (dict.find(tmp) != dict.end())
{
q.push(make_pair(tmp, step + 1));
dict.erase(tmp);
}
}
tmp[i] = old_ch;
}
}
return 0;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-623ee98952304b7e9b919c3d7e146a19",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "a8246082dcfb4ea5afea0cf24bb12dc2",
"author": "csdn.net",
"keywords": "字符串,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 分割回文串 II
<p>给你一个字符串 <code>s</code>,请你将 <code>s</code> 分割成一些子串,使每个子串都是回文。</p>
<p>返回符合要求的 <strong>最少分割次数</strong></p>
<div class="original__bRMd">
<div>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>s = "aab"
<strong>输出:</strong>1
<strong>解释:</strong>只需一次分割就可将 <em>s </em>分割成 ["aa","b"] 这样两个回文子串。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>s = "a"
<strong>输出:</strong>0
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>s = "ab"
<strong>输出:</strong>1
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= s.length <= 2000</code></li>
<li><code>s</code> 仅由小写英文字母组成</li>
</ul>
</div>
</div>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int minCut(string s)
{
const int N = s.size();
if (N <= 1)
return 0;
int i, j;
bool isPalin[N][N];
fill_n(&isPalin[0][0], N * N, false);
int minCuts[N + 1];
for (i = 0; i <= N; ++i)
minCuts[i] = i - 1;
for (j = 1; j < N; ++j)
{
for (i = j; i >= 0; --i)
{
if ((s[i] == s[j]) && ((j - i < 2) || isPalin[i + 1][j - 1]))
{
isPalin[i][j] = true;
minCuts[j + 1] = min(minCuts[j + 1], 1 + minCuts[i]);
}
}
}
return minCuts[N];
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-37990a05873740ab861f20f4e78be70b",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "11ebd5d979fb4925941083ff52136c4e",
"author": "csdn.net",
"keywords": "贪心,数组",
"notebook_enable": true
}
\ No newline at end of file
# 分发糖果
<p>老师想给孩子们分发糖果,有 <em>N</em> 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。</p>
<p>你需要按照以下要求,帮助老师给这些孩子分发糖果:</p>
<ul>
<li>每个孩子至少分配到 1 个糖果。</li>
<li>评分更高的孩子必须比他两侧的邻位孩子获得更多的糖果。</li>
</ul>
<p>那么这样下来,老师至少需要准备多少颗糖果呢?</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>[1,0,2]
<strong>输出:</strong>5
<strong>解释:</strong>你可以分别给这三个孩子分发 2、1、2 颗糖果。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>[1,2,2]
<strong>输出:</strong>4
<strong>解释:</strong>你可以分别给这三个孩子分发 1、2、1 颗糖果。
第三个孩子只得到 1 颗糖果,这已满足上述两个条件。</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int candy(vector<int> &ratings)
{
int len = ratings.size();
if (len < 2)
return len;
int candy[len + 1];
candy[0] = 1;
for (int i = 1; i < len; i++)
{
if (ratings[i] > ratings[i - 1])
candy[i] = candy[i - 1] + 1;
else
candy[i] = 1;
}
int ans = 0;
for (int i = len - 1; i > 0; i--)
{
if (candy[i] >= candy[i - 1] && ratings[i] < ratings[i - 1])
candy[i - 1] = max(candy[i - 1], candy[i] + 1);
ans += candy[i];
}
return ans + candy[0];
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-dc71d0ff18eb49d79792f969fe3e4e12",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "104810fc2b7b43be9636eda4d798839b",
"author": "csdn.net",
"keywords": "字典树,记忆化搜索,哈希表,字符串,动态规划,回溯",
"notebook_enable": true
}
\ No newline at end of file
# 单词拆分 II
<p>给定一个<strong>非空</strong>字符串 <em>s</em> 和一个包含<strong>非空</strong>单词列表的字典 <em>wordDict</em>,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。</p>
<p><strong>说明:</strong></p>
<ul>
<li>分隔时可以重复使用字典中的单词。</li>
<li>你可以假设字典中没有重复的单词。</li>
</ul>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:
</strong>s = &quot;<code>catsanddog</code>&quot;
wordDict = <code>[&quot;cat&quot;, &quot;cats&quot;, &quot;and&quot;, &quot;sand&quot;, &quot;dog&quot;]</code>
<strong>输出:
</strong><code>[
&nbsp; &quot;cats and dog&quot;,
&nbsp; &quot;cat sand dog&quot;
]</code>
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:
</strong>s = &quot;pineapplepenapple&quot;
wordDict = [&quot;apple&quot;, &quot;pen&quot;, &quot;applepen&quot;, &quot;pine&quot;, &quot;pineapple&quot;]
<strong>输出:
</strong>[
&nbsp; &quot;pine apple pen apple&quot;,
&nbsp; &quot;pineapple pen apple&quot;,
&nbsp; &quot;pine applepen apple&quot;
]
<strong>解释:</strong> 注意你可以重复使用字典中的单词。
</pre>
<p><strong>示例&nbsp;3:</strong></p>
<pre><strong>输入:
</strong>s = &quot;catsandog&quot;
wordDict = [&quot;cats&quot;, &quot;dog&quot;, &quot;sand&quot;, &quot;and&quot;, &quot;cat&quot;]
<strong>输出:
</strong>[]
</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<string> res;
unordered_set<string> wordset;
unordered_set<int> lenset;
vector<string> wordBreak(string s, vector<string> &wordDict)
{
for (const auto &w : wordDict)
{
wordset.insert(w);
lenset.insert(w.size());
}
vector<int> dp(s.size() + 1, 0);
dp[0] = 1;
for (int i = 1; i <= s.size(); ++i)
{
for (const auto &j : lenset)
{
if (i >= j && dp[i - j] && wordset.count(s.substr(i - j, j)))
dp[i] = 1;
}
}
if (dp.back() == 0)
return res;
backtrack(dp, 0, s, "");
return res;
}
void backtrack(vector<int> &dp, int idx, string &s, string tmp)
{
if (idx == s.size())
{
tmp.pop_back();
res.push_back(tmp);
return;
}
for (int i = idx + 1; i < dp.size(); ++i)
{
if (dp[i] == 1 && wordset.count(s.substr(idx, i - idx)))
{
backtrack(dp, i, s, tmp + s.substr(idx, i - idx) + " ");
}
}
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-19c4d2ed874a4229bed1cfffb35fa37c",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "3140fe1100a441829c2fa398e3987f00",
"author": "csdn.net",
"keywords": "几何,哈希表,数学",
"notebook_enable": true
}
\ No newline at end of file
# 直线上最多的点数
<p>给你一个数组 <code>points</code> ,其中 <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> 表示 <strong>X-Y</strong> 平面上的一个点。求最多有多少个点在同一条直线上。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg" style="width: 300px; height: 294px;" />
<pre>
<strong>输入:</strong>points = [[1,1],[2,2],[3,3]]
<strong>输出:</strong>3
</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/25/plane2.jpg" style="width: 300px; height: 294px;" />
<pre>
<strong>输入:</strong>points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
<strong>输出:</strong>4
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= points.length <= 300</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>4</sup> <= x<sub>i</sub>, y<sub>i</sub> <= 10<sup>4</sup></code></li>
<li><code>points</code> 中的所有点 <strong>互不相同</strong></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct Point
{
int x;
int y;
Point() : x(0), y(0) {}
Point(int a, int b) : x(a), y(b) {}
};
class Solution
{
public:
int maxPoints(vector<Point> &points)
{
int ans = 0;
for (int i = 0; i < points.size(); ++i)
{
map<pair<int, int>, int> m;
int p = 1;
for (int j = i + 1; j < points.size(); ++j)
{
if (points[i].x == points[j].x && (points[i].y == points[j].y))
{
++p;
continue;
}
int dx = points[j].x - points[i].x;
int dy = points[j].y - points[i].y;
int d = gcd(dx, dy);
++m[{dx / d, dy / d}];
}
ans = max(ans, p);
for (auto it = m.begin(); it != m.end(); ++it)
{
ans = max(ans, it->second + p);
}
}
return ans;
}
int gcd(int a, int b)
{
return (b == 0) ? a : gcd(b, a % b);
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-16b098a417204953a4caabb304f6db9f",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "eec0e728b9714adaa9f3b0d1958b3834",
"author": "csdn.net",
"keywords": "数组,二分查找",
"notebook_enable": true
}
\ No newline at end of file
# 寻找旋转排序数组中的最小值 II
已知一个长度为 <code>n</code> 的数组,预先按照升序排列,经由 <code>1</code><code>n</code><strong>旋转</strong> 后,得到输入数组。例如,原数组 <code>nums = [0,1,4,4,5,6,7]</code> 在变化后可能得到:
<ul>
<li>若旋转 <code>4</code> 次,则可以得到 <code>[4,5,6,7,0,1,4]</code></li>
<li>若旋转 <code>7</code> 次,则可以得到 <code>[0,1,4,4,5,6,7]</code></li>
</ul>
<p>注意,数组 <code>[a[0], a[1], a[2], ..., a[n-1]]</code> <strong>旋转一次</strong> 的结果为数组 <code>[a[n-1], a[0], a[1], a[2], ..., a[n-2]]</code></p>
<p>给你一个可能存在 <strong>重复</strong> 元素值的数组 <code>nums</code> ,它原来是一个升序排列的数组,并按上述情形进行了多次旋转。请你找出并返回数组中的 <strong>最小元素</strong></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>nums = [1,3,5]
<strong>输出:</strong>1
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [2,2,2,0,1]
<strong>输出:</strong>0
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 5000</code></li>
<li><code>-5000 <= nums[i] <= 5000</code></li>
<li><code>nums</code> 原来是一个升序排序的数组,并进行了 <code>1</code><code>n</code> 次旋转</li>
</ul>
<p> </p>
<p><strong>进阶:</strong></p>
<ul>
<li>这道题是 <a href="https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/description/">寻找旋转排序数组中的最小值</a> 的延伸题目。</li>
<li>允许重复会影响算法的时间复杂度吗?会如何影响,为什么?</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int findMin(vector<int> &nums)
{
int left = 0, right = nums.size() - 1;
while (left < right)
{
int mid = left + (right - left) / 2;
if (nums[mid] < nums[right])
right = mid;
else if (nums[mid] > nums[right])
left = mid + 1;
else if (nums[mid] == nums[right])
right--;
}
return nums[right];
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-d7a599592aa24aff848013c6ec15cf10",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "8ae901e74c254416b4765e3f64e86f2c",
"author": "csdn.net",
"keywords": "数组,桶排序,基数排序,排序",
"notebook_enable": true
}
\ No newline at end of file
# 最大间距
<p>给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。</p>
<p>如果数组元素个数小于 2,则返回 0。</p>
<p><strong>示例&nbsp;1:</strong></p>
<pre><strong>输入:</strong> [3,6,9,1]
<strong>输出:</strong> 3
<strong>解释:</strong> 排序后的数组是 [1,3,6,9]<strong><em>, </em></strong>其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。</pre>
<p><strong>示例&nbsp;2:</strong></p>
<pre><strong>输入:</strong> [10]
<strong>输出:</strong> 0
<strong>解释:</strong> 数组元素个数小于 2,因此返回 0。</pre>
<p><strong>说明:</strong></p>
<ul>
<li>你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。</li>
<li>请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maximumGap(vector<int> &nums)
{
set<int> st(nums.begin(), nums.end());
int res = 0, pre = INT_MIN;
for (auto iter = st.begin(); iter != st.end(); ++iter)
{
if (pre == INT_MIN)
{
pre = *iter;
continue;
}
else
{
res = max(res, *iter - pre);
pre = *iter;
}
}
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-296ab2fd88934525b5653ef7114a0358",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "7e1ff136064f405ea80673bf66bfbbfa",
"author": "csdn.net",
"keywords": "数组,动态规划,矩阵",
"notebook_enable": true
}
\ No newline at end of file
# 地下城游戏
<style>
table.dungeon, .dungeon th, .dungeon td {
border:3px solid black;
}
.dungeon th, .dungeon td {
text-align: center;
height: 70px;
width: 70px;
}
</style>
<p>一些恶魔抓住了公主(<strong>P</strong>)并将她关在了地下城的右下角。地下城是由&nbsp;M x N 个房间组成的二维网格。我们英勇的骑士(<strong>K</strong>)最初被安置在左上角的房间里,他必须穿过地下城并通过对抗恶魔来拯救公主。</p>
<p>骑士的初始健康点数为一个正整数。如果他的健康点数在某一时刻降至 0 或以下,他会立即死亡。</p>
<p>有些房间由恶魔守卫,因此骑士在进入这些房间时会失去健康点数(若房间里的值为<em>负整数</em>,则表示骑士将损失健康点数);其他房间要么是空的(房间里的值为 <em>0</em>),要么包含增加骑士健康点数的魔法球(若房间里的值为<em>正整数</em>,则表示骑士将增加健康点数)。</p>
<p>为了尽快到达公主,骑士决定每次只向右或向下移动一步。</p>
<p>&nbsp;</p>
<p><strong>编写一个函数来计算确保骑士能够拯救到公主所需的最低初始健康点数。</strong></p>
<p>例如,考虑到如下布局的地下城,如果骑士遵循最佳路径 <code>右 -&gt; 右 -&gt; 下 -&gt;</code>,则骑士的初始健康点数至少为 <strong>7</strong></p>
<table class="dungeon">
<tr>
<td>-2 (K)</td>
<td>-3</td>
<td>3</td>
</tr>
<tr>
<td>-5</td>
<td>-10</td>
<td>1</td>
</tr>
<tr>
<td>10</td>
<td>30</td>
<td>-5 (P)</td>
</tr>
</table>
<!---2K -3 3
-5 -10 1
10 30 5P-->
<p>&nbsp;</p>
<p><strong>说明:</strong></p>
<ul>
<li>
<p>骑士的健康点数没有上限。</p>
</li>
<li>任何房间都可能对骑士的健康点数造成威胁,也可能增加骑士的健康点数,包括骑士进入的左上角房间以及公主被监禁的右下角房间。</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int calculateMinimumHP(vector<vector<int>> &dungeon)
{
int row = dungeon.size();
int col = dungeon[0].size();
int dp[row][col] = {0};
dp[row - 1][col - 1] = max(1 - dungeon[row - 1][col - 1], 1);
for (int i = row - 2; i >= 0; i--)
{
dp[i][col - 1] = max(dp[i + 1][col - 1] - dungeon[i][col - 1], 1);
}
for (int i = col - 2; i >= 0; i--)
{
dp[row - 1][i] = max(dp[row - 1][i + 1] - dungeon[row - 1][i], 1);
}
for (int i = row - 2; i >= 0; i--)
{
for (int j = col - 2; j >= 0; j--)
{
dp[i][j] = max(min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j], 1);
}
}
return dp[0][0];
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-4aeca3661ce143d0bbfd73f6e72f11e9",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "72ab423ada734563aa9655cef722af73",
"author": "csdn.net",
"keywords": "数组,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 买卖股票的最佳时机 IV
<p>给定一个整数数组 <code>prices</code> ,它的第<em> </em><code>i</code> 个元素 <code>prices[i]</code> 是一支给定的股票在第 <code>i</code><em> </em>天的价格。</p>
<p>设计一个算法来计算你所能获取的最大利润。你最多可以完成 <strong>k</strong> 笔交易。</p>
<p><strong>注意:</strong>你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>k = 2, prices = [2,4,1]
<strong>输出:</strong>2
<strong>解释:</strong>在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>k = 2, prices = [3,2,6,5,0,3]
<strong>输出:</strong>7
<strong>解释:</strong>在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。
随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 <= k <= 100</code></li>
<li><code>0 <= prices.length <= 1000</code></li>
<li><code>0 <= prices[i] <= 1000</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxProfit(int k, vector<int> &prices)
{
const int len = prices.size();
if (len <= 1 || k == 0)
return 0;
if (k > len / 2)
k = len / 2;
const int count = k;
int buy[count];
int sell[count];
for (int i = 0; i < count; ++i)
{
buy[i] = -prices[0];
sell[i] = 0;
}
for (int i = 1; i < len; ++i)
{
buy[0] = max(buy[0], -prices[i]);
sell[0] = max(sell[0], buy[0] + prices[i]);
for (int j = count - 1; j > 0; --j)
{
buy[j] = max(buy[j], sell[j - 1] - prices[i]);
sell[j] = max(buy[j] + prices[i], sell[j]);
}
}
return sell[count - 1];
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-ab7610050b14427bb38fe76c6e8710c5",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "25f9587f51f1491795478d8603b141c9",
"author": "csdn.net",
"keywords": "字典树,数组,字符串,回溯,矩阵",
"notebook_enable": true
}
\ No newline at end of file
# 单词搜索 II
<p>给定一个 <code>m x n</code> 二维字符网格 <code>board</code><strong> </strong>和一个单词(字符串)列表 <code>words</code>,找出所有同时在二维网格和字典中出现的单词。</p>
<p>单词必须按照字母顺序,通过 <strong>相邻的单元格</strong> 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/07/search1.jpg" style="width: 322px; height: 322px;" />
<pre>
<strong>输入:</strong>board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
<strong>输出:</strong>["eat","oath"]
</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/07/search2.jpg" style="width: 162px; height: 162px;" />
<pre>
<strong>输入:</strong>board = [["a","b"],["c","d"]], words = ["abcb"]
<strong>输出:</strong>[]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>m == board.length</code></li>
<li><code>n == board[i].length</code></li>
<li><code>1 <= m, n <= 12</code></li>
<li><code>board[i][j]</code> 是一个小写英文字母</li>
<li><code>1 <= words.length <= 3 * 10<sup>4</sup></code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>words[i]</code> 由小写英文字母组成</li>
<li><code>words</code> 中的所有字符串互不相同</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
struct Node
{
bool isflag = false;
Node *next[27] = {};
};
set<string> res;
vector<string> ans;
Node *root;
vector<int> dirx{0, 0, 1, -1};
vector<int> diry{1, -1, 0, 0};
bool flag;
void createtree(vector<string> &words)
{
root = new Node();
for (auto w : words)
{
Node *p = root;
for (int i = 0; i < w.length(); i++)
{
if (p->next[w[i] - 'a'] == NULL)
{
p->next[w[i] - 'a'] = new Node();
}
p = p->next[w[i] - 'a'];
}
p->isflag = true;
}
}
void backtrack(vector<vector<char>> &board, vector<vector<bool>> visited, int row, int col, Node *roott, string cur)
{
cur += board[row][col];
roott = roott->next[board[row][col] - 'a'];
if (!roott)
return;
if (roott->isflag == true)
{
res.insert(cur);
flag = true;
}
visited[row][col] = true;
for (int i = 0; i < 4; i++)
{
int nx = row + dirx[i];
int ny = col + diry[i];
if (nx < 0 || ny < 0 || nx >= board.size() || ny >= board[0].size())
continue;
if (visited[nx][ny] == false)
{
backtrack(board, visited, nx, ny, roott, cur);
}
}
}
vector<string> findWords(vector<vector<char>> &board, vector<string> &words)
{
if (board.size() == 0 || words.size() == 0)
return ans;
createtree(words);
for (int i = 0; i < board.size(); i++)
{
for (int j = 0; j < board[i].size(); j++)
{
Node *p = root;
flag = false;
if (p->next[board[i][j] - 'a'])
{
vector<vector<bool>> visited{board.size(), vector<bool>(board[0].size(), false)};
backtrack(board, visited, i, j, p, "");
}
}
}
set<string>::iterator it;
for (it = res.begin(); it != res.end(); it++)
ans.push_back(*it);
return ans;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-cd6a68f0c68849f2be19d401b84309db",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "b23f7ff732e7454e84bac4dba3cf95da",
"author": "csdn.net",
"keywords": "字符串,字符串匹配,哈希函数,滚动哈希",
"notebook_enable": true
}
\ No newline at end of file
# 最短回文串
<p>给定一个字符串 <em><strong>s</strong></em>,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>s = "aacecaaa"
<strong>输出:</strong>"aaacecaaa"
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>s = "abcd"
<strong>输出:</strong>"dcbabcd"
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 <= s.length <= 5 * 10<sup>4</sup></code></li>
<li><code>s</code> 仅由小写英文字母组成</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
string shortestPalindrome(string s)
{
string rev(s);
reverse(rev.begin(), rev.end());
;
string combine = s + "#" + rev;
vector<int> lps(combine.length(), 0);
int remove = getLPS(combine, lps);
string prepend = rev.substr(0, rev.length() - remove);
return prepend + s;
}
int getLPS(string s, vector<int> &lps)
{
int j = 0, i = 1;
while (i < s.length())
{
if (s[i] == s[j])
{
lps[i] = j + 1;
i++;
j++;
}
else
{
if (j != 0)
{
j = lps[j - 1];
}
else
{
lps[i] = 0;
i++;
}
}
}
return lps[lps.size() - 1];
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-572dd30849c445fe93450dec47c48694",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "cb4c1989571145b3a29409a0eddf00ad",
"author": "csdn.net",
"keywords": "树状数组,线段树,数组,分治,有序集合,扫描线,堆(优先队列)",
"notebook_enable": true
}
\ No newline at end of file
# 天际线问题
<p>城市的天际线是从远处观看该城市中所有建筑物形成的轮廓的外部轮廓。给你所有建筑物的位置和高度,请返回由这些建筑物形成的<strong> 天际线</strong></p>
<p>每个建筑物的几何信息由数组 <code>buildings</code> 表示,其中三元组 <code>buildings[i] = [lefti, righti, heighti]</code> 表示:</p>
<ul>
<li><code>left<sub>i</sub></code> 是第 <code>i</code> 座建筑物左边缘的 <code>x</code> 坐标。</li>
<li><code>right<sub>i</sub></code> 是第 <code>i</code> 座建筑物右边缘的 <code>x</code> 坐标。</li>
<li><code>height<sub>i</sub></code> 是第 <code>i</code> 座建筑物的高度。</li>
</ul>
<p><strong>天际线</strong> 应该表示为由 “关键点” 组成的列表,格式 <code>[[x<sub>1</sub>,y<sub>1</sub>],[x<sub>2</sub>,y<sub>2</sub>],...]</code> ,并按 <strong>x 坐标 </strong>进行 <strong>排序</strong><strong>关键点是水平线段的左端点</strong>。列表中最后一个点是最右侧建筑物的终点,<code>y</code> 坐标始终为 <code>0</code> ,仅用于标记天际线的终点。此外,任何两个相邻建筑物之间的地面都应被视为天际线轮廓的一部分。</p>
<p><strong>注意:</strong>输出天际线中不得有连续的相同高度的水平线。例如 <code>[...[2 3], [4 5], [7 5], [11 5], [12 7]...]</code> 是不正确的答案;三条高度为 5 的线应该在最终输出中合并为一个:<code>[...[2 3], [4 5], [12 7], ...]</code></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/12/01/merged.jpg" style="width: 800px; height: 331px;" />
<pre>
<strong>输入:</strong>buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
<strong>输出:</strong>[[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
<strong>解释:</strong>
图 A<strong> </strong>显示输入的所有建筑物的位置和高度,
图 B 显示由这些建筑物形成的天际线。图 B 中的红点表示输出列表中的关键点。</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>buildings = [[0,2,3],[2,5,3]]
<strong>输出:</strong>[[0,3],[5,0]]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= buildings.length <= 10<sup>4</sup></code></li>
<li><code>0 <= left<sub>i</sub> < right<sub>i</sub> <= 2<sup>31</sup> - 1</code></li>
<li><code>1 <= height<sub>i</sub> <= 2<sup>31</sup> - 1</code></li>
<li><code>buildings</code><code>left<sub>i</sub></code> 非递减排序</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<pair<int, int>> getSkyline(vector<vector<int>> &buildings)
{
vector<pair<int, int>> h, res;
multiset<int> m;
int pre = 0, cur = 0;
for (auto &a : buildings)
{
h.push_back({a[0], -a[2]});
h.push_back({a[1], a[2]});
}
sort(h.begin(), h.end());
m.insert(0);
for (auto &a : h)
{
if (a.second < 0)
m.insert(-a.second);
else
m.erase(m.find(a.second));
cur = *m.rbegin();
if (cur != pre)
{
res.push_back({a.first, cur});
pre = cur;
}
}
return res;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-88bbdbf9e14241978caed8e0c240060b",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "baff5b234a504bae989fd669da2cfe46",
"author": "csdn.net",
"keywords": "栈,递归,数学,字符串",
"notebook_enable": true
}
\ No newline at end of file
# 基本计算器
<p>给你一个字符串表达式 <code>s</code> ,请你实现一个基本计算器来计算并返回它的值。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>s = "1 + 1"
<strong>输出:</strong>2
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>s = " 2-1 + 2 "
<strong>输出:</strong>3
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>s = "(1+(4+5+2)-3)+(6+8)"
<strong>输出:</strong>23
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= s.length <= * 10<sup>5</sup></code></li>
<li><code>s</code> 由数字、<code>'+'</code><code>'-'</code><code>'('</code><code>')'</code>、和 <code>' '</code> 组成</li>
<li><code>s</code> 表示一个有效的表达式</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int calculate(string s)
{
stack<int> myStack;
stack<char> myOperator;
int i;
for (i = 0; i < s.length(); i++)
{
while (i < s.length() && s[i] == ' ')
i++;
if (i == s.length())
break;
if (s[i] == '+' || s[i] == '-' || s[i] == '(')
myOperator.push(s[i]);
else if (s[i] == ')')
{
while (myOperator.top() != '(')
{
int element1 = myStack.top();
myStack.pop();
int element2 = myStack.top();
myStack.pop();
char op = myOperator.top();
myOperator.pop();
if (op == '+')
myStack.push(element1 + element2);
else if (op == '-')
myStack.push(element2 - element1);
}
if (!myOperator.empty())
myOperator.pop();
while (!myOperator.empty() && (myOperator.top() != '('))
{
int element1 = myStack.top();
myStack.pop();
int element2 = myStack.top();
myStack.pop();
char op = myOperator.top();
myOperator.pop();
if (op == '+')
myStack.push(element1 + element2);
else if (op == '-')
myStack.push(element2 - element1);
}
}
else
{
long long int number = 0;
int j = i;
while (j < s.length() && (s[j] - '0' <= 9) && (s[j] - '0' >= 0))
{
number = number * 10 + (s[j] - '0');
j++;
}
i = j - 1;
myStack.push(number);
while (!myOperator.empty() && (myOperator.top() != '('))
{
int element1 = myStack.top();
myStack.pop();
int element2 = myStack.top();
myStack.pop();
char op = myOperator.top();
myOperator.pop();
if (op == '+')
myStack.push(element1 + element2);
else if (op == '-')
myStack.push(element2 - element1);
}
}
}
return myStack.top();
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-61f9fc10dc864281b7a95db6089242dd",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "b5a670ea8b284444ba5acb0d328c5c97",
"author": "csdn.net",
"keywords": "递归,数学,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 数字 1 的个数
<p>给定一个整数 <code>n</code>,计算所有小于等于 <code>n</code> 的非负整数中数字 <code>1</code> 出现的个数。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>n = 13
<strong>输出:</strong>6
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>n = 0
<strong>输出:</strong>0
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int countDigitOne(int n)
{
int cnt = 0;
for (long int i = 1; i <= n; i *= 10)
{
int a = n / i, b = n % i;
cnt += (a + 8) / 10 * i + (a % 10 == 1) * (b + 1);
if (i == 1000000000)
break;
}
return cnt;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-7a317eb4490c473090a047305ef60283",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "3b27126a94db47f5ac7e185667a33344",
"author": "csdn.net",
"keywords": "队列,数组,滑动窗口,单调队列,堆(优先队列)",
"notebook_enable": true
}
\ No newline at end of file
# 滑动窗口最大值
<p>给你一个整数数组 <code>nums</code>,有一个大小为 <code>k</code><em> </em>的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 <code>k</code> 个数字。滑动窗口每次只向右移动一位。</p>
<p>返回滑动窗口中的最大值。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<b>输入:</b>nums = [1,3,-1,-3,5,3,6,7], k = 3
<b>输出:</b>[3,3,5,5,6,7]
<b>解释:</b>
滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 <strong>3</strong>
1 [3 -1 -3] 5 3 6 7 <strong>3</strong>
1 3 [-1 -3 5] 3 6 7 <strong> 5</strong>
1 3 -1 [-3 5 3] 6 7 <strong>5</strong>
1 3 -1 -3 [5 3 6] 7 <strong>6</strong>
1 3 -1 -3 5 [3 6 7] <strong>7</strong>
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<b>输入:</b>nums = [1], k = 1
<b>输出:</b>[1]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<b>输入:</b>nums = [1,-1], k = 1
<b>输出:</b>[1,-1]
</pre>
<p><strong>示例 4:</strong></p>
<pre>
<b>输入:</b>nums = [9,11], k = 2
<b>输出:</b>[11]
</pre>
<p><strong>示例 5:</strong></p>
<pre>
<b>输入:</b>nums = [4,-2], k = 2
<b>输出:</b>[4]</pre>
<p> </p>
<p><b>提示:</b></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
<li><code>1 <= k <= nums.length</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k)
{
vector<int> ans;
int n = nums.size();
if (n == 0 || k > n)
return ans;
deque<int> que;
for (int i = 0; i < n; i++)
{
if (!que.empty())
{
if (i >= que.front() + k)
que.pop_front();
while (!que.empty() && nums[i] >= nums[que.back()])
que.pop_back();
}
que.push_back(i);
if (i + 1 >= k)
ans.push_back(nums[que.front()]);
}
return ans;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-25cba8fca30740af8a49256efbf594cb",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "3d2ccc106fcd41818fd74fb68c3e8298",
"author": "csdn.net",
"keywords": "递归,数学,字符串",
"notebook_enable": true
}
\ No newline at end of file
# 整数转换英文表示
<p>将非负整数 <code>num</code> 转换为其对应的英文表示。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>num = 123
<strong>输出:</strong>"One Hundred Twenty Three"
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>num = 12345
<strong>输出:</strong>"Twelve Thousand Three Hundred Forty Five"
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>num = 1234567
<strong>输出:</strong>"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
</pre>
<p><strong>示例 4:</strong></p>
<pre>
<strong>输入:</strong>num = 1234567891
<strong>输出:</strong>"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 <= num <= 2<sup>31</sup> - 1</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
const int Mod[3] = {1000000000, 1000000, 1000};
string H[3] = {"Billion", "Million", "Thousand"},
M[8] = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"},
L[20] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
void update(string &ans)
{
ans += ans == "" ? "" : " ";
}
string numberToWords2(int num)
{
if (num < 20)
return L[num];
string ans;
if (num >= 100)
ans += L[num / 100] + " Hundred", num %= 100;
if (num == 0)
return ans;
else if (num < 20)
update(ans), ans += L[num];
else
{
update(ans), ans += M[num / 10 - 2], num %= 10;
if (num == 0)
return ans;
else
update(ans), ans += L[num];
}
return ans;
}
string numberToWords(int num)
{
if (num < 20)
return L[num];
string ans;
for (int i = 0; i < 3; ++i)
if (num >= Mod[i])
update(ans), ans += numberToWords2(num / Mod[i]) + " " + H[i], num %= Mod[i];
if (num)
update(ans), ans += numberToWords2(num);
return ans;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-9148dd1d0d824227a0f66243065d8d5e",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "fae69384ffea4b4fb4c8a9c37d8a967e",
"author": "csdn.net",
"keywords": "数学,字符串,回溯",
"notebook_enable": true
}
\ No newline at end of file
# 给表达式添加运算符
<p>给定一个仅包含数字&nbsp;<code>0-9</code>&nbsp;的字符串 <code>num</code> 和一个目标值整数 <code>target</code> ,在 <code>num</code> 的数字之间添加 <strong>二元 </strong>运算符(不是一元)<code>+</code><code>-</code>&nbsp;&nbsp;<code>*</code>&nbsp;,返回所有能够得到目标值的表达式。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> <code>num = </code>"123", target = 6
<strong>输出: </strong>["1+2+3", "1*2*3"]
</pre>
<p><strong>示例&nbsp;2:</strong></p>
<pre>
<strong>输入:</strong> <code>num = </code>"232", target = 8
<strong>输出: </strong>["2*3+2", "2+3*2"]</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong> <code>num = </code>"105", target = 5
<strong>输出: </strong>["1*0+5","10-5"]</pre>
<p><strong>示例&nbsp;4:</strong></p>
<pre>
<strong>输入:</strong> <code>num = </code>"00", target = 0
<strong>输出: </strong>["0+0", "0-0", "0*0"]
</pre>
<p><strong>示例 5:</strong></p>
<pre>
<strong>输入:</strong> <code>num = </code>"3456237490", target = 9191
<strong>输出: </strong>[]</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= num.length &lt;= 10</code></li>
<li><code>num</code> 仅含数字</li>
<li><code>-2<sup>31</sup> &lt;= target &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<string> addOperators(string num, int target)
{
vector<string> res;
addOperatorsDFS(num, target, 0, 0, "", res);
return res;
}
void addOperatorsDFS(string num, int target, long long diff, long long curNum, string out, vector<string> &res)
{
if (num.size() == 0 && curNum == target)
res.push_back(out);
for (int i = 1; i <= num.size(); ++i)
{
string cur = num.substr(0, i);
if (cur.size() > 1 && cur[0] == '0')
return;
string next = num.substr(i);
if (out.size() > 0)
{
addOperatorsDFS(next, target, stoll(cur), curNum + stoll(cur), out + "+" + cur, res);
addOperatorsDFS(next, target, -stoll(cur), curNum - stoll(cur), out + "-" + cur, res);
addOperatorsDFS(next, target, diff * stoll(cur), (curNum - diff) + diff * stoll(cur), out + "*" + cur, res);
}
else
addOperatorsDFS(next, target, stoll(cur), stoll(cur), cur, res);
}
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-ed64cc102b034228bec7cdbf38c44a99",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "dcec5a48b80b494c91f58f095646b76f",
"author": "csdn.net",
"keywords": "设计,双指针,数据流,排序,堆(优先队列)",
"notebook_enable": true
}
\ No newline at end of file
# 数据流的中位数
<p>中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。</p>
<p>例如,</p>
<p>[2,3,4]&nbsp;的中位数是 3</p>
<p>[2,3] 的中位数是 (2 + 3) / 2 = 2.5</p>
<p>设计一个支持以下两种操作的数据结构:</p>
<ul>
<li>void addNum(int num) - 从数据流中添加一个整数到数据结构中。</li>
<li>double findMedian() - 返回目前所有元素的中位数。</li>
</ul>
<p><strong>示例:</strong></p>
<pre>addNum(1)
addNum(2)
findMedian() -&gt; 1.5
addNum(3)
findMedian() -&gt; 2</pre>
<p><strong>进阶:</strong></p>
<ol>
<li>如果数据流中所有整数都在 0 到 100 范围内,你将如何优化你的算法?</li>
<li>如果数据流中 99% 的整数都在 0 到 100 范围内,你将如何优化你的算法?</li>
</ol>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class MedianFinder
{
public:
/** initialize your data structure here. */
MedianFinder()
{
}
void addNum(int num)
{
auto it = upper_bound(nums.begin(), nums.end(), num);
nums.insert(it, num);
}
double findMedian()
{
int n = nums.size();
if (n % 2 == 0)
return 1.0 * (nums[n / 2 - 1] + nums[n / 2]) / 2;
else
return nums[n / 2];
}
vector<int> nums;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-b8f9e08b8157416f913906073262a9c6",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "17181b7f3c6849748a23d6d9a1a9df15",
"author": "csdn.net",
"keywords": "树,深度优先搜索,广度优先搜索,设计,字符串,二叉树",
"notebook_enable": true
}
\ No newline at end of file
# 二叉树的序列化与反序列化
<p>序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。</p>
<p>请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。</p>
<p><strong>提示: </strong>输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅 <a href="/faq/#binary-tree">LeetCode 序列化二叉树的格式</a>。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/serdeser.jpg" style="width: 442px; height: 324px;" />
<pre>
<strong>输入:</strong>root = [1,2,3,null,null,4,5]
<strong>输出:</strong>[1,2,3,null,null,4,5]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>root = []
<strong>输出:</strong>[]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>root = [1]
<strong>输出:</strong>[1]
</pre>
<p><strong>示例 4:</strong></p>
<pre>
<strong>输入:</strong>root = [1,2]
<strong>输出:</strong>[1,2]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中结点数在范围 <code>[0, 10<sup>4</sup>]</code></li>
<li><code>-1000 <= Node.val <= 1000</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Codec
{
public:
string serialize(TreeNode *root)
{
if (!root)
return "#_";
return to_string(root->val) + "_" + serialize(root->left) + serialize(root->right);
}
TreeNode *deserialize(string data)
{
cout << data << endl;
queue<string> q;
stringstream ss(data);
string s;
while (getline(ss, s, '_'))
q.push(s);
return help(q);
}
TreeNode *help(queue<string> &q)
{
auto cur = q.front();
q.pop();
if (cur == "#")
return NULL;
auto root = new TreeNode(stoi(cur));
root->left = help(q);
root->right = help(q);
return root;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-19e15a33245e42a0b1aa4c31ee5dc348",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "7f6ed006b6be477e8d0ad716b0fdc2ce",
"author": "csdn.net",
"keywords": "广度优先搜索,字符串,回溯",
"notebook_enable": true
}
\ No newline at end of file
# 删除无效的括号
<p>给你一个由若干括号和字母组成的字符串 <code>s</code> ,删除最小数量的无效括号,使得输入的字符串有效。</p>
<p>返回所有可能的结果。答案可以按 <strong>任意顺序</strong> 返回。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>s = "()())()"
<strong>输出:</strong>["(())()","()()()"]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>s = "(a)())()"
<strong>输出:</strong>["(a())()","(a)()()"]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>s = ")("
<strong>输出:</strong>[""]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= s.length <= 25</code></li>
<li><code>s</code> 由小写英文字母以及括号 <code>'('</code><code>')'</code> 组成</li>
<li><code>s</code> 中至多含 <code>20</code> 个括号</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<string> removeInvalidParentheses(string s)
{
vector<string> ans;
rm(move(s), ans, {'(', ')'}, 0, 0);
if (ans.empty())
return {""};
return ans;
}
void rm(string s, vector<string> &ans, vector<char> brackets, int sea_i, int del_i)
{
int sta = 0;
for (int i = sea_i; i < s.size(); i++)
{
if (s[i] == brackets[0])
sta++;
else if (s[i] == brackets[1])
{
sta--;
if (sta < 0)
{
for (int j = del_i; j <= i; j++)
{
if (s[j] == brackets[1] && (j == del_i || s[j - 1] != brackets[1]))
{
string new_s = s.substr(0, j) + s.substr(j + 1);
rm(move(new_s), ans, brackets, i, j);
}
}
return;
}
}
}
reverse(s.begin(), s.end());
if (brackets[0] == '(')
rm(move(s), ans, {brackets[1], brackets[0]}, 0, 0);
else
ans.push_back(move(s));
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-f41308ed84bb4ef8ad09e564348c103f",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "8b8699849ba949a28d934e908e7e0fa0",
"author": "csdn.net",
"keywords": "数组,动态规划",
"notebook_enable": true
}
\ No newline at end of file
# 戳气球
<p><code>n</code> 个气球,编号为<code>0</code><code>n - 1</code>,每个气球上都标有一个数字,这些数字存在数组 <code>nums</code> 中。</p>
<p>现在要求你戳破所有的气球。戳破第 <code>i</code> 个气球,你可以获得 <code>nums[i - 1] * nums[i] * nums[i + 1]</code> 枚硬币。 这里的 <code>i - 1</code><code>i + 1</code> 代表和 <code>i</code> 相邻的两个气球的序号。如果 <code>i - 1</code><code>i + 1</code> 超出了数组的边界,那么就当它是一个数字为 <code>1</code> 的气球。</p>
<p>求所能获得硬币的最大数量。</p>
<p> </p>
<strong>示例 1:</strong>
<pre>
<strong>输入:</strong>nums = [3,1,5,8]
<strong>输出:</strong>167
<strong>解释:</strong>
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [1,5]
<strong>输出:</strong>10
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 500</code></li>
<li><code>0 <= nums[i] <= 100</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxCoins(vector<int> &nums)
{
vector<int> dpnums(nums.size() + 2, 1);
for (int i = 0, j = 1; i < nums.size(); i++, j++)
dpnums[j] = nums[i];
vector<vector<int>> coins(dpnums.size(), vector<int>(dpnums.size(), 0));
for (int i = 2; i < dpnums.size(); i++)
{
for (int j = 0; j + i < dpnums.size(); j++)
{
for (int k = j + 1; k < j + i; k++)
{
coins[j][j + i] = max(coins[j][j + i], coins[j][k] + coins[k][j + i] +
dpnums[j] * dpnums[k] * dpnums[j + i]);
}
}
}
return coins[0][dpnums.size() - 1];
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-d574cf192da6469f948a09a9d97a071a",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "e89ac694c7044313854e7b7bb303b131",
"author": "csdn.net",
"keywords": "树状数组,线段树,数组,二分查找,分治,有序集合,归并排序",
"notebook_enable": true
}
\ No newline at end of file
# 计算右侧小于当前元素的个数
<p>给你`一个整数数组 <code>nums</code><em> </em>,按要求返回一个新数组&nbsp;<code>counts</code><em> </em>。数组 <code>counts</code> 有该性质: <code>counts[i]</code> 的值是&nbsp; <code>nums[i]</code> 右侧小于&nbsp;<code>nums[i]</code> 的元素的数量。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>nums = [5,2,6,1]
<strong>输出:</strong><code>[2,1,1,0]
<strong>解释:</strong></code>
5 的右侧有 <strong>2 </strong>个更小的元素 (2 和 1)
2 的右侧仅有 <strong>1 </strong>个更小的元素 (1)
6 的右侧有 <strong>1 </strong>个更小的元素 (1)
1 的右侧有 <strong>0 </strong>个更小的元素
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [-1]
<strong>输出:</strong>[0]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>nums = [-1,-1]
<strong>输出:</strong>[0,0]
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
struct BSTNode
{
int val;
int count;
BSTNode *left;
BSTNode *right;
BSTNode(int x) : val(x), left(NULL), right(NULL), count(0) {}
};
void BST_insert(BSTNode *node, BSTNode *insert_node, int &count_small)
{
if (insert_node->val <= node->val)
{
node->count++;
if (node->left)
{
BST_insert(node->left, insert_node, count_small);
}
else
{
node->left = insert_node;
}
}
else
{
count_small += node->count + 1;
if (node->right)
{
BST_insert(node->right, insert_node, count_small);
}
else
{
node->right = insert_node;
}
}
}
vector<int> countSmaller(vector<int> &nums)
{
vector<int> result;
vector<BSTNode *> node_vec;
vector<int> count;
for (int i = nums.size() - 1; i >= 0; i--)
{
node_vec.push_back(new BSTNode(nums[i]));
}
count.push_back(0);
for (int i = 1; i < node_vec.size(); i++)
{
int count_small = 0;
BST_insert(node_vec[0], node_vec[i], count_small);
count.push_back(count_small);
}
for (int i = node_vec.size() - 1; i >= 0; i--)
{
delete node_vec[i];
result.push_back(count[i]);
}
return result;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-d2a1b7ad02a34771b7a2f90f7a9ea1ca",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "1ef1ec9da93d458db404ae7309cc1885",
"author": "csdn.net",
"keywords": "栈,贪心,单调栈",
"notebook_enable": true
}
\ No newline at end of file
# 拼接最大数
<p>给定长度分别为&nbsp;<code>m</code>&nbsp;&nbsp;<code>n</code>&nbsp;的两个数组,其元素由&nbsp;<code>0-9</code>&nbsp;构成,表示两个自然数各位上的数字。现在从这两个数组中选出 <code>k (k &lt;= m + n)</code>&nbsp;个数字拼接成一个新的数,要求从同一个数组中取出的数字保持其在原数组中的相对顺序。</p>
<p>求满足该条件的最大数。结果返回一个表示该最大数的长度为&nbsp;<code>k</code>&nbsp;的数组。</p>
<p><strong>说明: </strong>请尽可能地优化你算法的时间和空间复杂度。</p>
<p><strong>示例&nbsp;1:</strong></p>
<pre><strong>输入:</strong>
nums1 = <code>[3, 4, 6, 5]</code>
nums2 = <code>[9, 1, 2, 5, 8, 3]</code>
k = <code>5</code>
<strong>输出:</strong>
<code>[9, 8, 6, 5, 3]</code></pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong>
nums1 = <code>[6, 7]</code>
nums2 = <code>[6, 0, 4]</code>
k = <code>5</code>
<strong>输出:</strong>
<code>[6, 7, 6, 0, 4]</code></pre>
<p><strong>示例 3:</strong></p>
<pre><strong>输入:</strong>
nums1 = <code>[3, 9]</code>
nums2 = <code>[8, 9]</code>
k = <code>3</code>
<strong>输出:</strong>
<code>[9, 8, 9]</code></pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> maxNumber(vector<int> &nums1, vector<int> &nums2, int k)
{
vector<int> ans;
const int n1 = nums1.size();
const int n2 = nums2.size();
for (int k1 = 0; k1 <= k; ++k1)
{
const int k2 = k - k1;
if (k1 > n1 || k2 > n2)
{
continue;
}
ans = max(ans, maxNumber(maxNumber(nums1, k1), maxNumber(nums2, k2)));
}
return ans;
}
private:
vector<int> maxNumber(const vector<int> &nums, const int k)
{
if (k == 0)
{
return {};
}
vector<int> ans;
int to_pop = nums.size() - k;
for (const int num : nums)
{
while (!ans.empty() && num > ans.back() && to_pop-- > 0)
{
ans.pop_back();
}
ans.push_back(num);
}
ans.resize(k);
return ans;
}
vector<int> maxNumber(const vector<int> &nums1, const vector<int> &nums2)
{
vector<int> ans;
auto s1 = nums1.cbegin();
auto e1 = nums1.cend();
auto s2 = nums2.cbegin();
auto e2 = nums2.cend();
while (s1 != e1 || s2 != e2)
{
ans.push_back(lexicographical_compare(s1, e1, s2, e2) ? *s2++ : *s1++);
}
return ans;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-e8d6d5215fc946fe8126be057a8f33bf",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "49d7e248a7104b43a2bcb42d3d72d75f",
"author": "csdn.net",
"keywords": "树状数组,线段树,数组,二分查找,分治,有序集合,归并排序",
"notebook_enable": true
}
\ No newline at end of file
# 区间和的个数
<p>给你一个整数数组 <code>nums</code> 以及两个整数 <code>lower</code><code>upper</code> 。求数组中,值位于范围 <code>[lower, upper]</code> (包含 <code>lower</code> 和 <code>upper</code>)之内的 <strong>区间和的个数</strong></p>
<p><strong>区间和</strong> <code>S(i, j)</code> 表示在 <code>nums</code> 中,位置从 <code>i</code> 到 <code>j</code> 的元素之和,包含 <code>i</code> 和 <code>j</code> (<code>i</code><code>j</code>)。</p>
<p> </p>
<strong>示例 1:</strong>
<pre>
<strong>输入:</strong>nums = [-2,5,-1], lower = -2, upper = 2
<strong>输出:</strong>3
<strong>解释:</strong>存在三个区间:[0,0]、[2,2] 和 [0,2] ,对应的区间和分别是:-2 、-1 、2 。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [0], lower = 0, upper = 0
<strong>输出:</strong>1
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>-10<sup>5</sup> <= lower <= upper <= 10<sup>5</sup></code></li>
<li>题目数据保证答案是一个 <strong>32 位</strong> 的整数</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int countRangeSum(vector<int> &nums, int lower, int upper)
{
int n = nums.size();
long presum = 0;
multiset<long> S;
S.insert(0);
int ret = 0;
for (int i = 0; i < n; i++)
{
presum += nums[i];
ret += distance(S.lower_bound(presum - upper), S.upper_bound(presum - lower));
S.insert(presum);
}
return ret;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-3f5b93af46c448b8ae7f658f71441265",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{ {
"type": "code_options", "type": "code_options",
"source": "solution.md", "source": "solution.md",
"exercise_id": "62801b47b45a4a19bfcc15f52214ba61", "exercise_id": "5671bc1bbdd14985ab0221672b319317",
"author": "csdn.net", "author": "csdn.net",
"keywords": "深度优先搜索,广度优先搜索,图,拓扑排序,数组,字符串" "keywords": "深度优先搜索,广度优先搜索,图,拓扑排序,记忆化搜索,动态规划",
"notebook_enable": true
} }
\ No newline at end of file
# 矩阵中的最长递增路径
<p>给定一个 <code>m x n</code> 整数矩阵 <code>matrix</code> ,找出其中 <strong>最长递增路径</strong> 的长度。</p>
<p>对于每个单元格,你可以往上,下,左,右四个方向移动。 你 <strong>不能</strong><strong>对角线</strong> 方向上移动或移动到 <strong>边界外</strong>(即不允许环绕)。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/05/grid1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>输入:</strong>matrix = [[9,9,4],[6,6,8],[2,1,1]]
<strong>输出:</strong>4
<strong>解释:</strong>最长递增路径为 <code>[1, 2, 6, 9]</code></pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/27/tmp-grid.jpg" style="width: 253px; height: 253px;" />
<pre>
<strong>输入:</strong>matrix = [[3,4,5],[3,2,6],[2,2,1]]
<strong>输出:</strong>4
<strong>解释:</strong>最长递增路径是 <code>[3, 4, 5, 6]</code>。注意不允许在对角线方向上移动。
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>matrix = [[1]]
<strong>输出:</strong>1
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= matrix[i][j] <= 2<sup>31</sup> - 1</code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
static constexpr int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int m, n;
int longestIncreasingPath(vector<vector<int>> &matrix)
{
if (matrix.size() == 0 || matrix[0].size() == 0)
{
return 0;
}
m = matrix.size();
n = matrix[0].size();
int res = 0;
auto memo = vector<vector<int>>(m, vector<int>(n, 0));
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (memo[i][j])
res = max(res, memo[i][j]);
else
res = max(res, dfs(i, j, matrix, memo));
}
}
return res;
}
int dfs(int i, int j, vector<vector<int>> &matrix, vector<vector<int>> &memo)
{
int temp = 1;
for (int k = 0; k < 4; ++k)
{
int x = i + dirs[k][0];
int y = j + dirs[k][1];
if ((x >= 0) && (x < m) && (y >= 0) && (y < n) && (matrix[i][j] < matrix[x][y]))
{
if (memo[x][y])
temp = max(temp, memo[x][y] + 1);
else
temp = max(temp, dfs(x, y, matrix, memo) + 1);
}
}
memo[i][j] = temp;
return temp;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-2ccf8bd80a7549a88c59b83b0a4784cc",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "a5843164b52e4063aaaf7002f5f24ace",
"author": "csdn.net",
"keywords": "贪心,数组",
"notebook_enable": true
}
\ No newline at end of file
# 按要求补齐数组
<p>给定一个已排序的正整数数组 <em>nums,</em>和一个正整数&nbsp;<em>n 。</em>&nbsp;<code>[1, n]</code>&nbsp;区间内选取任意个数字补充到&nbsp;<em>nums&nbsp;</em>中,使得&nbsp;<code>[1, n]</code>&nbsp;区间内的任何数字都可以用&nbsp;<em>nums&nbsp;</em>中某几个数字的和来表示。请输出满足上述要求的最少需要补充的数字个数。</p>
<p><strong>示例&nbsp;1:</strong></p>
<pre><strong>输入: </strong><em>nums</em> = <code>[1,3]</code>, <em>n</em> = <code>6</code>
<strong>输出: </strong>1
<strong>解释:</strong>
根据<em> nums&nbsp;</em>里现有的组合&nbsp;<code>[1], [3], [1,3]</code>,可以得出&nbsp;<code>1, 3, 4</code>
现在如果我们将&nbsp;<code>2</code>&nbsp;添加到&nbsp;<em>nums 中,</em>&nbsp;组合变为: <code>[1], [2], [3], [1,3], [2,3], [1,2,3]</code>
其和可以表示数字&nbsp;<code>1, 2, 3, 4, 5, 6</code>,能够覆盖&nbsp;<code>[1, 6]</code>&nbsp;区间里所有的数。
所以我们最少需要添加一个数字。</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入: </strong><em>nums</em> = <code>[1,5,10]</code>, <em>n</em> = <code>20</code>
<strong>输出:</strong> 2
<strong>解释: </strong>我们需要添加&nbsp;<code>[2, 4]</code>
</pre>
<p><strong>示例&nbsp;3:</strong></p>
<pre><strong>输入: </strong><em>nums</em> = <code>[1,2,2]</code>, <em>n</em> = <code>5</code>
<strong>输出:</strong> 0
</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int minPatches(vector<int> &nums, int n)
{
long max_sum = 0;
int m = nums.size();
int cnt = 0;
for (long i = 1, pos = 0; i <= n;)
{
if (pos >= m || i < nums[pos])
{
cnt++;
max_sum += i;
}
else
{
max_sum += nums[pos];
pos++;
}
i = max_sum + 1;
}
return cnt;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-cbca99701aee469abf36e38ed0f2f36e",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "bcb282c1b7944d67a230d8907c37384c",
"author": "csdn.net",
"keywords": "几何,数组,数学",
"notebook_enable": true
}
\ No newline at end of file
# 路径交叉
<p>给你一个整数数组 <code>distance</code><em> </em></p>
<p><strong>X-Y</strong> 平面上的点&nbsp;<code>(0,0)</code>&nbsp;开始,先向北移动 <code>distance[0]</code> 米,然后向西移动 <code>distance[1]</code> 米,向南移动 <code>distance[2]</code> 米,向东移动 <code>distance[3]</code> 米,持续移动。也就是说,每次移动后你的方位会发生逆时针变化。</p>
<p>判断你所经过的路径是否相交。如果相交,返回 <code>true</code> ;否则,返回 <code>false</code></p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/selfcross1-plane.jpg" style="width: 400px; height: 435px;" />
<pre>
<strong>输入:</strong>distance = [2,1,1,2]
<strong>输出:</strong>true
</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/selfcross2-plane.jpg" style="width: 400px; height: 435px;" />
<pre>
<strong>输入:</strong>distance = [1,2,3,4]
<strong>输出:</strong>false
</pre>
<p><strong>示例 3:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/selfcross3-plane.jpg" style="width: 400px; height: 435px;" />
<pre>
<strong>输入:</strong>distance = [1,1,1,1]
<strong>输出:</strong>true</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;=&nbsp;distance.length &lt;= 10<sup>5</sup></code></li>
<li><code>1 &lt;=&nbsp;distance[i] &lt;= 10<sup>5</sup></code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isSelfCrossing(vector<int> &distance)
{
int all_step = distance.size(), current_step = 0;
if (all_step < 4)
return false;
current_step = 2;
while (current_step < all_step && distance[current_step] > distance[current_step - 2])
current_step++;
if (current_step == all_step)
return false;
if (distance[current_step] >= distance[current_step - 2] - (current_step > 3 ? distance[current_step - 4] : 0))
distance[current_step - 1] -= current_step > 2 ? distance[current_step - 3] : 0;
current_step++;
while (current_step < all_step && distance[current_step] < distance[current_step - 2])
current_step++;
return current_step != all_step;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-71f21c0d662d4ea3a6d46384c908cce6",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "7c4227d3d4b340a789a82bf09cd8a2e4",
"author": "csdn.net",
"keywords": "字典树,数组,哈希表,字符串",
"notebook_enable": true
}
\ No newline at end of file
# 回文对
<p>给定一组<strong> 互不相同</strong> 的单词, 找出所有<strong> 不同<em> </em></strong>的索引对 <code>(i, j)</code>,使得列表中的两个单词, <code>words[i] + words[j]</code> ,可拼接成回文串。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>words = ["abcd","dcba","lls","s","sssll"]
<strong>输出:</strong>[[0,1],[1,0],[3,2],[2,4]]
<strong>解释:</strong>可拼接成的回文串为 <code>["dcbaabcd","abcddcba","slls","llssssll"]</code>
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>words = ["bat","tab","cat"]
<strong>输出:</strong>[[0,1],[1,0]]
<strong>解释:</strong>可拼接成的回文串为 <code>["battab","tabbat"]</code></pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>words = ["a",""]
<strong>输出:</strong>[[0,1],[1,0]]
</pre>
 
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= words.length <= 5000</code></li>
<li><code>0 <= words[i].length <= 300</code></li>
<li><code>words[i]</code> 由小写英文字母组成</li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<vector<int>> palindromePairs(vector<string> &words)
{
vector<vector<int>> res;
unordered_map<string, int> m;
set<int> s;
for (int i = 0; i < words.size(); ++i)
{
m[words[i]] = i;
s.insert(words[i].size());
}
for (int i = 0; i < words.size(); ++i)
{
string t = words[i];
int len = t.size();
reverse(t.begin(), t.end());
if (m.count(t) && m[t] != i)
{
res.push_back({i, m[t]});
}
auto a = s.find(len);
for (auto it = s.begin(); it != a; ++it)
{
int d = *it;
if (isValid(t, 0, len - d - 1) && m.count(t.substr(len - d)))
{
res.push_back({i, m[t.substr(len - d)]});
}
if (isValid(t, d, len - 1) && m.count(t.substr(0, d)))
{
res.push_back({m[t.substr(0, d)], i});
}
}
}
return res;
}
bool isValid(string t, int left, int right)
{
while (left < right)
{
if (t[left++] != t[right--])
return false;
}
return true;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-fbeb14ccb2ad450f92f803197d8a2898",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "4d13553202dd4ff3a8b913e7fcbfdebc",
"author": "csdn.net",
"keywords": "设计,二分查找,有序集合",
"notebook_enable": true
}
\ No newline at end of file
# 将数据流变为多个不相交区间
<p>&nbsp;给你一个由非负整数&nbsp;<code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code> 组成的数据流输入,请你将到目前为止看到的数字总结为不相交的区间列表。</p>
<p>实现 <code>SummaryRanges</code> 类:</p>
<div class="original__bRMd">
<div>
<ul>
<li><code>SummaryRanges()</code> 使用一个空数据流初始化对象。</li>
<li><code>void addNum(int val)</code> 向数据流中加入整数 <code>val</code></li>
<li><code>int[][] getIntervals()</code> 以不相交区间&nbsp;<code>[start<sub>i</sub>, end<sub>i</sub>]</code> 的列表形式返回对数据流中整数的总结。</li>
</ul>
<p>&nbsp;</p>
<p><strong>示例:</strong></p>
<pre>
<strong>输入:</strong>
["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"]
[[], [1], [], [3], [], [7], [], [2], [], [6], []]
<strong>输出:</strong>
[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]
<strong>解释:</strong>
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = [1]
summaryRanges.getIntervals(); // 返回 [[1, 1]]
summaryRanges.addNum(3); // arr = [1, 3]
summaryRanges.getIntervals(); // 返回 [[1, 1], [3, 3]]
summaryRanges.addNum(7); // arr = [1, 3, 7]
summaryRanges.getIntervals(); // 返回 [[1, 1], [3, 3], [7, 7]]
summaryRanges.addNum(2); // arr = [1, 2, 3, 7]
summaryRanges.getIntervals(); // 返回 [[1, 3], [7, 7]]
summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]
summaryRanges.getIntervals(); // 返回 [[1, 3], [6, 7]]
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 &lt;= val &lt;= 10<sup>4</sup></code></li>
<li>最多调用&nbsp;<code>addNum</code><code>getIntervals</code> 方法 <code>3 * 10<sup>4</sup></code></li>
</ul>
</div>
</div>
<p>&nbsp;</p>
<p><strong>进阶:</strong>如果存在大量合并,并且与数据流的大小相比,不相交区间的数量很小,该怎么办?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class SummaryRanges
{
public:
vector<vector<int>> ans;
unordered_map<int, int> use;
int size;
/** Initialize your data structure here. */
SummaryRanges()
{
size = 0;
}
void addNum(int val)
{
if (use.count(val) != 0)
return;
use[val] = 1;
int i;
for (i = 0; i < size; i++)
if (val < ans[i][0])
break;
if (i == 0)
{
if (size == 0)
{
ans.insert(ans.begin(), {val, val});
size++;
}
else if (val + 1 == ans[i][0])
ans[0][0] = val;
else
{
ans.insert(ans.begin(), {val, val});
size++;
}
}
else if (i == size)
{
if (val - 1 == ans[i - 1][1])
ans[i - 1][1] = val;
else
{
ans.push_back({val, val});
size++;
}
}
else
{
if (val + 1 != ans[i][0] && val - 1 != ans[i - 1][1])
{
ans.insert(ans.begin() + i, {val, val});
size++;
}
else if (val + 1 == ans[i][0] && val - 1 == ans[i - 1][1])
{
ans[i - 1][1] = ans[i][1];
ans.erase(ans.begin() + i);
size--;
}
else if (val + 1 == ans[i][0])
{
ans[i][0] = val;
}
else
{
ans[i - 1][1] = val;
}
}
}
vector<vector<int>> getIntervals()
{
return ans;
}
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges* obj = new SummaryRanges();
* obj->addNum(val);
* vector<vector<int>> param_2 = obj->getIntervals();
*/
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-42f27fdeec37424a8f341b005c5817ad",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "87cb6f4e87f44caba4be82fa4c1458aa",
"author": "csdn.net",
"keywords": "数组,二分查找,动态规划,排序",
"notebook_enable": true
}
\ No newline at end of file
# 俄罗斯套娃信封问题
<p>给你一个二维整数数组 <code>envelopes</code> ,其中 <code>envelopes[i] = [w<sub>i</sub>, h<sub>i</sub>]</code> ,表示第 <code>i</code> 个信封的宽度和高度。</p>
<p>当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。</p>
<p>请计算 <strong>最多能有多少个</strong> 信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。</p>
<p><strong>注意</strong>:不允许旋转信封。</p>
 
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>envelopes = [[5,4],[6,4],[6,7],[2,3]]
<strong>输出:</strong>3
<strong>解释:</strong>最多信封的个数为 <code>3, 组合为: </code>[2,3] => [5,4] => [6,7]。</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>envelopes = [[1,1],[1,1],[1,1]]
<strong>输出:</strong>1
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= envelopes.length <= 5000</code></li>
<li><code>envelopes[i].length == 2</code></li>
<li><code>1 <= w<sub>i</sub>, h<sub>i</sub> <= 10<sup>4</sup></code></li>
</ul>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxEnvelopes(vector<vector<int>> &envelopes)
{
sort(envelopes.begin(), envelopes.end(), comp);
vector<int> dp(envelopes.size(), 1);
for (int i = 0; i < envelopes.size(); ++i)
{
for (int j = 0; j < i; ++j)
{
if (envelopes[i][1] > envelopes[j][1])
dp[i] = dp[i] > dp[j] + 1 ? dp[i] : dp[j] + 1;
}
}
int res = 0;
for (int i = 0; i < dp.size(); ++i)
res = res > dp[i] ? res : dp[i];
return res;
}
static bool comp(const vector<int> &a, const vector<int> &b)
{
if (a[0] < b[0])
return true;
else if (a[0] > b[0])
return false;
else
{
if (a[1] > b[1])
return true;
else
return false;
}
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-aef821a970104bb790aa7151f2738112",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "a4236763673c4399aa681854f79513e3",
"author": "csdn.net",
"keywords": "数组,二分查找,动态规划,矩阵,有序集合",
"notebook_enable": true
}
\ No newline at end of file
# 矩形区域不超过 K 的最大数值和
<p>给你一个 <code>m x n</code> 的矩阵 <code>matrix</code> 和一个整数 <code>k</code> ,找出并返回矩阵内部矩形区域的不超过 <code>k</code> 的最大数值和。</p>
<p>题目数据保证总会存在一个数值和不超过 <code>k</code> 的矩形区域。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg" style="width: 255px; height: 176px;" />
<pre>
<strong>输入:</strong>matrix = [[1,0,1],[0,-2,3]], k = 2
<strong>输出:</strong>2
<strong>解释:</strong>蓝色边框圈出来的矩形区域 <code>[[0, 1], [-2, 3]]</code> 的数值和是 2,且 2 是不超过 k 的最大数字(k = 2)。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>matrix = [[2,2,-1]], k = 3
<strong>输出:</strong>3
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>-100 <= matrix[i][j] <= 100</code></li>
<li><code>-10<sup>5</sup> <= k <= 10<sup>5</sup></code></li>
</ul>
<p> </p>
<p><strong>进阶:</strong>如果行数远大于列数,该如何设计解决方案?</p>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxSumSubmatrix(vector<vector<int>> &mat, int k)
{
int m = mat.size(), n = mat[0].size();
vector<vector<int>> sum(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + mat[i - 1][j - 1];
}
}
int ans = INT_MIN;
for (int top = 1; top <= m; top++)
{
for (int bot = top; bot <= m; bot++)
{
set<int> st;
st.insert(0);
for (int r = 1; r <= n; r++)
{
int right = sum[bot][r] - sum[top - 1][r];
auto left = st.lower_bound(right - k);
if (left != st.end())
{
int cur = right - *left;
ans = max(ans, cur);
}
st.insert(right);
}
}
}
return ans;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-a90c9ada239046bca1194d2abb4df6c4",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "cc8a49e3be2d49f49effc7e672eed57a",
"author": "csdn.net",
"keywords": "数组,扫描线",
"notebook_enable": true
}
\ No newline at end of file
# 完美矩形
<p>我们有 N 个与坐标轴对齐的矩形, 其中 N &gt; 0, 判断它们是否能精确地覆盖一个矩形区域。</p>
<p>每个矩形用左下角的点和右上角的点的坐标来表示。例如,&nbsp;一个单位正方形可以表示为 [1,1,2,2]。&nbsp;( 左下角的点的坐标为 (1, 1) 以及右上角的点的坐标为 (2, 2) )。</p>
<p><img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/22/rectangle_perfect.gif"></p>
<p><strong>示例 1:</strong></p>
<pre>rectangles = [
[1,1,3,3],
[3,1,4,2],
[3,2,4,4],
[1,3,2,4],
[2,3,3,4]
]
返回 true。5个矩形一起可以精确地覆盖一个矩形区域。
</pre>
<p>&nbsp;</p>
<p><img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/22/rectangle_separated.gif"></p>
<p><strong>示例&nbsp;2:</strong></p>
<pre>rectangles = [
[1,1,2,3],
[1,3,2,4],
[3,1,4,2],
[3,2,4,4]
]
返回 false。两个矩形之间有间隔,无法覆盖成一个矩形。
</pre>
<p>&nbsp;</p>
<p><img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/22/rectangle_hole.gif"></p>
<p><strong>示例 3:</strong></p>
<pre>rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[3,2,4,4]
]
返回 false。图形顶端留有间隔,无法覆盖成一个矩形。
</pre>
<p>&nbsp;</p>
<p><img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/22/rectangle_intersect.gif"></p>
<p><strong>示例 4:</strong></p>
<pre>rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[2,2,4,4]
]
返回 false。因为中间有相交区域,虽然形成了矩形,但不是精确覆盖。
</pre>
## template
```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isRectangleCover(vector<vector<int>> &ret)
{
set<pair<int, int>> s;
int x1 = INT_MAX, y1 = INT_MAX, x2 = INT_MIN, y2 = INT_MIN, area = 0;
for (int i = 0; i < ret.size(); ++i)
{
x1 = min(ret[i][0], x1);
x2 = max(ret[i][2], x2);
y1 = min(ret[i][1], y1);
y2 = max(ret[i][3], y2);
area += (ret[i][2] - ret[i][0]) * (ret[i][3] - ret[i][1]);
if (s.find({ret[i][0], ret[i][1]}) == s.end())
s.insert({ret[i][0], ret[i][1]});
else
s.erase({ret[i][0], ret[i][1]});
if (s.find({ret[i][2], ret[i][3]}) == s.end())
s.insert({ret[i][2], ret[i][3]});
else
s.erase({ret[i][2], ret[i][3]});
if (s.find({ret[i][0], ret[i][3]}) == s.end())
s.insert({ret[i][0], ret[i][3]});
else
s.erase({ret[i][0], ret[i][3]});
if (s.find({ret[i][2], ret[i][1]}) == s.end())
s.insert({ret[i][2], ret[i][1]});
else
s.erase({ret[i][2], ret[i][1]});
}
if (s.size() != 4 || !s.count({x1, y1}) || !s.count({x1, y2}) || !s.count({x2, y1}) || !s.count({x2, y2}))
return false;
return area == (x2 - x1) * (y2 - y1);
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
因为 它太大了无法显示 source diff 。你可以改为 查看blob
...@@ -29,7 +29,48 @@ ...@@ -29,7 +29,48 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int>> levelOrder(TreeNode *root)
{
if (root == NULL)
return {};
queue<TreeNode *> queue;
TreeNode *p = root;
vector<vector<int>> res;
queue.push(p);
while (queue.empty() == false)
{
vector<int> temp = {};
int length = queue.size();
for (int i = 0; i < length; i++)
{
p = queue.front();
queue.pop();
temp.push_back(p->val);
if (p->left)
queue.push(p->left);
if (p->right)
queue.push(p->right);
}
res.push_back(temp);
}
return res;
}
};
``` ```
......
...@@ -27,6 +27,53 @@ ...@@ -27,6 +27,53 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int>> zigzagLevelOrder(TreeNode *root)
{
if (!root)
return {};
vector<vector<int>> res;
vector<int> temp;
int level = 0;
queue<pair<TreeNode *, int>> q;
q.push(pair(root, 0));
while (!q.empty())
{
TreeNode *node = q.front().first;
level = q.front().second;
q.pop();
if (res.size() < level)
{
if (level % 2 == 0)
reverse(temp.begin(), temp.end());
res.push_back(temp);
temp.clear();
}
temp.push_back(node->val);
if (node->left)
q.push(pair(node->left, level + 1));
if (node->right)
q.push(pair(node->right, level + 1));
}
if (level % 2 != 0)
reverse(temp.begin(), temp.end());
res.push_back(temp);
return res;
}
};
``` ```
......
...@@ -36,7 +36,48 @@ ...@@ -36,7 +36,48 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
private:
unordered_map<int, int> inMap;
public:
TreeNode *myBuildTree(vector<int> &preorder, int preStart, int preEnd, vector<int> &inorder, int inStart, int inEnd)
{
if (preStart > preEnd)
return nullptr;
TreeNode *root = new TreeNode(preorder[preStart]);
int inRoot = inMap[preorder[preStart]];
int numsLeft = inRoot - inStart;
root->left = myBuildTree(preorder, preStart + 1, preStart + numsLeft, inorder, inStart, inRoot - 1);
root->right = myBuildTree(preorder, preStart + numsLeft + 1, preEnd, inorder, inRoot + 1, inEnd);
return root;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder)
{
int n = preorder.size();
for (int i = 0; i < n; i++)
{
inMap[inorder[i]] = i;
}
return myBuildTree(preorder, 0, n - 1, inorder, 0, n - 1);
}
};
``` ```
......
...@@ -23,7 +23,50 @@ ...@@ -23,7 +23,50 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
{
if (0 == inorder.size() || 0 == postorder.size())
{
return NULL;
}
return build(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
}
TreeNode *build(vector<int> &inorder, int i1, int i2, vector<int> &postorder, int p1, int p2)
{
TreeNode *root = new TreeNode(postorder[p2]);
int i = i1;
while (i <= i2 && postorder[p2] != inorder[i])
{
i++;
}
int left = i - i1;
int right = i2 - i;
if (left > 0)
{
root->left = build(inorder, i1, i - 1, postorder, p1, p1 + left - 1);
}
if (right > 0)
{
root->right = build(inorder, i + 1, i2, postorder, p1 + left, p2 - 1);
}
return root;
}
};
``` ```
......
...@@ -27,7 +27,48 @@ ...@@ -27,7 +27,48 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int>> levelOrderBottom(TreeNode *root)
{
vector<vector<int>> res;
if (root == NULL)
return res;
queue<TreeNode *> q;
q.push(root);
while (!q.empty())
{
vector<int> oneLevel;
int size = q.size();
for (int i = 0; i < size; i++)
{
TreeNode *node = q.front();
q.pop();
oneLevel.push_back(node->val);
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
}
res.insert(res.begin(), oneLevel);
}
return res;
}
};
``` ```
......
...@@ -21,6 +21,49 @@ ...@@ -21,6 +21,49 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
vector<int> nums;
TreeNode *create(int low, int high)
{
if (low > high)
return NULL;
int mid = (low + high) / 2;
auto root = new TreeNode(nums[mid]);
root->left = create(low, mid - 1);
root->right = create(mid + 1, high);
return root;
}
TreeNode *sortedListToBST(ListNode *head)
{
while (head)
{
nums.push_back(head->val);
head = head->next;
}
return create(0, nums.size() - 1);
}
};
``` ```
......
...@@ -45,6 +45,58 @@ ...@@ -45,6 +45,58 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int>> pathSum(TreeNode *root, int sum)
{
vector<vector<int>> res;
vector<int> track;
backTrack(root, res, track, sum);
return res;
}
void backTrack(TreeNode *root, vector<vector<int>> &res, vector<int> track, int sum)
{
if (!root)
{
return;
}
if (!root->left && !root->right)
{
sum -= root->val;
track.push_back(root->val);
if (sum == 0)
{
res.push_back(track);
}
track.pop_back();
sum += root->val;
return;
}
sum -= root->val;
track.push_back(root->val);
backTrack(root->left, res, track, sum);
backTrack(root->right, res, track, sum);
track.pop_back();
sum += root->val;
}
};
``` ```
......
...@@ -47,7 +47,42 @@ ...@@ -47,7 +47,42 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
void rconnect(TreeNode *&node, TreeNode *pmove)
{
if (pmove == nullptr)
return;
node->right = new TreeNode(pmove->val);
node->left = nullptr;
node = node->right;
rconnect(node, pmove->left);
rconnect(node, pmove->right);
}
void flatten(TreeNode *root)
{
if (root == nullptr)
return;
TreeNode *head = new TreeNode();
TreeNode *newroot = head;
rconnect(head, root);
newroot = newroot->right->right;
root->right = newroot;
root->left = nullptr;
}
};
``` ```
......
...@@ -48,7 +48,59 @@ struct Node { ...@@ -48,7 +48,59 @@ struct Node {
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node *left;
Node *right;
Node *next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node *_left, Node *_right, Node *_next)
: val(_val), left(_left), right(_right), next(_next) {}
};
class Solution
{
public:
Node *connect(Node *root)
{
if (!root)
return nullptr;
root->next = nullptr;
connect_helper(root);
return root;
}
private:
void connect_helper(Node *pNode)
{
if (!pNode)
return;
if (pNode->left == nullptr)
return;
pNode->left->next = pNode->right;
if (pNode->right == nullptr)
return;
if (pNode->next != nullptr)
pNode->right->next = pNode->next->left;
else
pNode->right->next = nullptr;
connect_helper(pNode->left);
connect_helper(pNode->right);
}
};
``` ```
......
...@@ -52,6 +52,53 @@ struct Node { ...@@ -52,6 +52,53 @@ struct Node {
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node *left;
Node *right;
Node *next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node *_left, Node *_right, Node *_next)
: val(_val), left(_left), right(_right), next(_next) {}
};
class Solution
{
public:
Node *connect(Node *root)
{
if (!root)
return NULL;
Node *p = root->next;
while (p)
{
if (p->left)
{
p = p->left;
break;
}
if (p->right)
{
p = p->right;
break;
}
p = p->next;
}
if (root->right)
root->right->next = p;
if (root->left)
root->left->next = root->right ? root->right : p;
connect(root->right);
connect(root->left);
return root;
}
};
``` ```
......
...@@ -49,7 +49,47 @@ ...@@ -49,7 +49,47 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int minimumTotal(vector<vector<int>> &triangle)
{
int n = triangle.size();
if (n == 0)
return 0;
if (n == 1)
return triangle[0][0];
vector<vector<int>> info(n, vector<int>(n, 0));
info[0][0] = triangle[0][0];
for (int i = 1; i < n; ++i)
{
for (int j = 0; j <= i; ++j)
{
if (j == 0)
info[i][j] = triangle[i][j] + info[i - 1][j];
else if (j == i)
info[i][j] = triangle[i][j] + info[i - 1][j - 1];
else
{
int temp = info[i - 1][j] > info[i - 1][j - 1] ? info[i - 1][j - 1] : info[i - 1][j];
info[i][j] = temp + triangle[i][j];
}
}
}
int res = info[n - 1][0];
for (int i = 0; i < n; ++i)
{
if (info[n - 1][i] < res)
{
res = info[n - 1][i];
}
}
return res;
}
};
``` ```
......
...@@ -33,7 +33,44 @@ ...@@ -33,7 +33,44 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int longestConsecutive(vector<int> &nums)
{
unordered_set<int> s;
for (auto v : nums)
s.insert(v);
int res = 0;
for (auto v : nums)
{
if (s.find(v) != s.end())
{
s.erase(v);
int temp = 1;
int cur = v;
while (s.find(cur - 1) != s.end())
{
cur--;
s.erase(cur);
}
temp += v - cur;
cur = v;
while (s.find(cur + 1) != s.end())
{
cur++;
s.erase(cur);
}
temp += cur - v;
res = max(res, temp);
}
}
return res;
}
};
``` ```
......
...@@ -53,6 +53,59 @@ ...@@ -53,6 +53,59 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int sumNumbers(TreeNode *root)
{
if (root == nullptr)
return 0;
int result = 0;
vector<int> num;
vector<int> temp;
digui(root, &num, &temp);
for (int i = 0; i < num.size(); i++)
{
result = result + num[i];
}
return result;
}
void digui(TreeNode *root, vector<int> *num, vector<int> *temp)
{
temp->push_back(root->val);
if (root->left == nullptr && root->right == nullptr)
{
int sum = 0;
for (int i = temp->size() - 1; i >= 0; i--)
{
/*if (i==0 && (*temp)[0]==0) {
continue;
}*/
int howi = (*temp)[i];
sum = sum + howi * pow(10, (temp->size() - i - 1));
}
num->push_back(sum);
temp->pop_back();
return;
}
if (root->left)
digui(root->left, num, temp);
if (root->right)
digui(root->right, num, temp);
temp->pop_back();
}
};
``` ```
......
...@@ -37,6 +37,69 @@ ...@@ -37,6 +37,69 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int m, n;
void solve(vector<vector<char>> &board)
{
m = board.size();
if (!m)
return;
n = board[0].size();
if (!n)
return;
for (int i = 0; i < m; ++i)
{
if (i == 0 || i == m - 1)
{
for (int j = 0; j < n; ++j)
{
if (board[i][j] == 'O')
dfs(board, i, j);
}
}
else
{
if (board[i][0] == 'O')
dfs(board, i, 0);
if (board[i][n - 1] == 'O')
dfs(board, i, n - 1);
}
}
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
{
if (board[i][j] == 'A')
board[i][j] = 'O';
else
board[i][j] = 'X';
}
}
void dfs(vector<vector<char>> &board, int i, int j)
{
board[i][j] = 'A';
if (i - 1 < m && i - 1 >= 0 && j < n && j >= 0 && board[i - 1][j] == 'O')
{
dfs(board, i - 1, j);
}
if (i + 1 < m && i + 1 >= 0 && j < n && j >= 0 && board[i + 1][j] == 'O')
{
dfs(board, i + 1, j);
}
if (i < m && i >= 0 && j - 1 < n && j - 1 >= 0 && board[i][j - 1] == 'O')
{
dfs(board, i, j - 1);
}
if (i < m && i >= 0 && j + 1 < n && j + 1 >= 0 && board[i][j + 1] == 'O')
{
dfs(board, i, j + 1);
}
}
};
``` ```
......
...@@ -33,7 +33,46 @@ ...@@ -33,7 +33,46 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isPali(string s)
{
for (int i = 0; i < s.length() / 2; i++)
if (s[i] != s[s.length() - i - 1])
return false;
return true;
}
void dfs(vector<vector<string>> &ans, vector<string> &tmp, int n, string s)
{
if (n == s.length())
{
ans.push_back(tmp);
return;
}
for (int i = n; i < s.length(); i++)
{
if (isPali(s.substr(n, i - n + 1)))
{
tmp.push_back(s.substr(n, i - n + 1));
dfs(ans, tmp, i + 1, s);
tmp.pop_back();
}
}
}
vector<vector<string>> partition(string s)
{
vector<vector<string>> ans;
vector<string> tmp;
dfs(ans, tmp, 0, s);
return ans;
}
};
``` ```
......
...@@ -74,6 +74,47 @@ ...@@ -74,6 +74,47 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
vector<Node *> neighbors;
Node() {}
Node(int _val, vector<Node *> _neighbors)
{
val = _val;
neighbors = _neighbors;
}
};
class Solution
{
public:
Node *cloneGraph(Node *node)
{
unordered_map<Node *, Node *> m;
return helper(node, m);
}
Node *helper(Node *node, unordered_map<Node *, Node *> &m)
{
if (!node)
return NULL;
if (m.count(node))
return m[node];
Node *clone = new Node(node->val);
m[node] = clone;
for (Node *neighbor : node->neighbors)
{
clone->neighbors.push_back(helper(neighbor, m));
}
return clone;
}
};
``` ```
......
...@@ -51,6 +51,34 @@ cost = [3,4,3] ...@@ -51,6 +51,34 @@ cost = [3,4,3]
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
int index = 0;
int sum = 0;
int csum = 0;
for (int i = 0; i < gas.size(); i++)
{
int temp = gas[i] - cost[i];
sum += temp;
if (csum > 0)
{
csum += gas[i] - cost[i];
}
else
{
csum = gas[i] - cost[i];
index = i;
}
}
return sum >= 0 ? index : -1;
}
};
``` ```
......
...@@ -36,6 +36,39 @@ ...@@ -36,6 +36,39 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int singleNumber(vector<int> &nums)
{
sort(nums.begin(), nums.end());
int res = 0;
int i = 0;
for (int j = 1; j < nums.size(); j++)
{
if (nums[j] != nums[i])
{
if (j - i == 1)
{
res = nums[i];
break;
}
else
{
i = j;
}
}
}
if (i == nums.size() - 1)
{
res = nums[i];
}
return res;
}
};
``` ```
......
...@@ -68,6 +68,60 @@ ...@@ -68,6 +68,60 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node *next;
Node *random;
Node() {}
Node(int _val, Node *_next, Node *_random)
{
val = _val;
next = _next;
random = _random;
}
};
class Solution
{
public:
Node *copyRandomList(Node *head)
{
std::map<Node *, int> node_map;
std::vector<Node *> node_vec;
Node *ptr = head;
int i = 0;
while (ptr)
{
node_vec.push_back(new Node(ptr->val, NULL, NULL));
node_map[ptr] = i;
ptr = ptr->next;
i++;
}
node_vec.push_back(0);
ptr = head;
i = 0;
while (ptr)
{
node_vec[i]->next = node_vec[i + 1];
if (ptr->random)
{
int id = node_map[ptr->random];
node_vec[i]->random = node_vec[id];
}
ptr = ptr->next;
i++;
}
return node_vec[0];
}
};
``` ```
......
...@@ -34,7 +34,36 @@ ...@@ -34,7 +34,36 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool wordBreak(string s, vector<string> &wordDict)
{
map<string, int> tmp;
for (int i = 0; i < wordDict.size(); i++)
{
tmp[wordDict[i]]++;
}
int n = s.length();
vector<bool> res(n + 1, false);
res[0] = true;
for (int i = 0; i <= n; i++)
{
for (int j = 0; j < i; j++)
{
if (res[j] && tmp[s.substr(j, i - j)])
{
res[i] = true;
break;
}
}
}
return res[n];
}
};
``` ```
......
...@@ -58,6 +58,42 @@ ...@@ -58,6 +58,42 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
ListNode *slow, *fast, *p;
slow = fast = p = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
while (p != slow)
{
p = p->next;
slow = slow->next;
}
return p;
}
}
return nullptr;
}
};
``` ```
......
...@@ -40,6 +40,56 @@ ...@@ -40,6 +40,56 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
void reorderList(ListNode *head)
{
ListNode *l1 = head, *l2 = head;
ListNode *tep = head;
int len = 0;
while (tep)
{
len++;
tep = tep->next;
}
if (len <= 2)
return;
int len1 = len / 2 + len % 2;
int len2 = len / 2;
for (int i = 0; i < len1 - 1; i++)
{
head = head->next;
}
l2 = head->next;
head->next = nullptr;
head = l1;
stack<ListNode *> stk;
while (l2)
{
stk.push(l2);
l2 = l2->next;
}
while (!stk.empty())
{
tep = stk.top();
stk.pop();
tep->next = l1->next;
l1->next = tep;
l1 = tep->next;
}
}
};
``` ```
......
...@@ -57,6 +57,68 @@ lRUCache.get(4); // 返回 4 ...@@ -57,6 +57,68 @@ lRUCache.get(4); // 返回 4
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class LRUCache
{
private:
int _cap;
list<pair<int, int>> cache;
unordered_map<int, list<pair<int, int>>::iterator> umap;
public:
LRUCache(int capacity)
{
_cap = capacity;
}
int get(int key)
{
auto iter = umap.find(key);
if (iter == umap.end())
return -1;
pair<int, int> kv = *umap[key];
cache.erase(umap[key]);
cache.push_front(kv);
umap[key] = cache.begin();
return kv.second;
}
void put(int key, int value)
{
auto iter = umap.find(key);
if (iter != umap.end())
{
cache.erase(umap[key]);
cache.push_front(make_pair(key, value));
umap[key] = cache.begin();
return;
}
if (cache.size() == _cap)
{
auto iter = cache.back();
umap.erase(iter.first);
cache.pop_back();
cache.push_front(make_pair(key, value));
umap[key] = cache.begin();
}
else
{
cache.push_front(make_pair(key, value));
umap[key] = cache.begin();
}
}
};
``` ```
......
...@@ -34,6 +34,37 @@ ...@@ -34,6 +34,37 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *insertionSortList(ListNode *head)
{
ListNode *dummy = new ListNode(0, head);
ListNode
*prev = dummy,
*lastSorted = head,
*curr = head->next;
while (curr)
{
lastSorted->next = curr->next;
curr->next = prev->next;
prev->next = curr;
curr = lastSorted->next;
}
return dummy->next;
}
};
``` ```
......
...@@ -44,6 +44,63 @@ ...@@ -44,6 +44,63 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *sortList(ListNode *head)
{
return mergesort(head);
}
ListNode *mergesort(ListNode *node)
{
if (!node || !node->next)
return node;
ListNode *fast = node;
ListNode *slow = node;
ListNode *brek = node;
while (fast && fast->next)
{
fast = fast->next->next;
brek = slow;
slow = slow->next;
}
brek->next = nullptr;
ListNode *l1 = mergesort(node);
ListNode *l2 = mergesort(slow);
return merge(l1, l2);
}
ListNode *merge(ListNode *l1, ListNode *l2)
{
if (l1 == NULL)
{
return l2;
}
if (l2 == NULL)
{
return l1;
}
if (l1->val < l2->val)
{
l1->next = merge(l1->next, l2);
return l1;
}
else
{
l2->next = merge(l2->next, l1);
return l2;
}
}
};
``` ```
......
...@@ -77,6 +77,42 @@ ...@@ -77,6 +77,42 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
stack<int> num;
for (int i = 0; i < tokens.size(); ++i)
{
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
{
int j;
int a = num.top();
num.pop();
int b = num.top();
num.pop();
if (tokens[i] == "+")
j = b + a;
else if (tokens[i] == "-")
j = b - a;
else if (tokens[i] == "*")
j = b * a;
else
j = b / a;
num.push(j);
}
else
{
num.push(stoi(tokens[i]));
}
}
return num.top();
}
};
``` ```
......
...@@ -78,6 +78,58 @@ ...@@ -78,6 +78,58 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
string reverseWords(string s)
{
splitStr(s);
return joinStr();
}
private:
void splitStr(string s)
{
if (s == "")
return;
int len = s.length();
string tmp = "";
for (int i = 0; i < len; i++)
{
if (s[i] == ' ' && tmp != "")
{
myStack.push(tmp);
tmp = "";
continue;
}
if (s[i] == ' ')
continue;
tmp += s[i];
}
if (tmp != "")
myStack.push(tmp);
return;
}
string joinStr()
{
if (myStack.empty())
return "";
string s = "";
while (!myStack.empty())
{
s += myStack.top();
s += " ";
myStack.pop();
}
return s.substr(0, s.length() - 1);
}
stack<string> myStack;
};
``` ```
......
...@@ -21,6 +21,28 @@ ...@@ -21,6 +21,28 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxProduct(vector<int> &nums)
{
int ans = -10000000;
int n = nums.size();
int max1 = 1, min1 = 1, mx, mn;
for (int i = 0; i < n; i++)
{
mx = max1;
mn = min1;
max1 = max(mx * nums[i], max(nums[i], mn * nums[i]));
min1 = min(mn * nums[i], min(nums[i], mx * nums[i]));
ans = max(max1, ans);
}
return ans;
}
};
``` ```
......
...@@ -52,6 +52,27 @@ ...@@ -52,6 +52,27 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int findMin(vector<int> &nums)
{
int left = 0, right = nums.size() - 1;
int mid = (left + right) / 2;
while (left < right)
{
mid = (left + right) / 2;
if (nums[mid] > nums[right])
left = mid + 1;
else
right = mid;
}
return nums[left];
}
};
``` ```
......
# 上下翻转二叉树
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
# 至多包含两个不同字符的最长子串
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
# 相隔为 1 的编辑距离
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -41,6 +41,36 @@ ...@@ -41,6 +41,36 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int findPeakElement(vector<int> &nums)
{
int l = 0, r = nums.size() - 1;
while (l < r)
{
int mid = l + (r - l) / 2;
if (nums[mid] > nums[mid + 1])
{
if (mid == 0 || nums[mid] > nums[mid - 1])
return mid;
else
r = mid;
}
else
{
if (mid + 1 == nums.size() - 1 || nums[mid + 1] > nums[mid + 2])
return mid + 1;
else
l = mid + 1;
}
}
return l;
}
};
``` ```
......
...@@ -69,7 +69,49 @@ ...@@ -69,7 +69,49 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int compareVersion(string version1, string version2)
{
int val1, val2;
int idx1 = 0, idx2 = 0;
while (idx1 < version1.length() || idx2 < version2.length())
{
val1 = 0;
while (idx1 < version1.length())
{
if (version1[idx1] == '.')
{
++idx1;
break;
}
val1 = val1 * 10 + (version1[idx1] - '0');
idx1++;
}
val2 = 0;
while (idx2 < version2.length())
{
if (version2[idx2] == '.')
{
idx2++;
break;
}
val2 = val2 * 10 + (version2[idx2] - '0');
idx2++;
}
if (val1 > val2)
return 1;
if (val1 < val2)
return -1;
}
return 0;
}
};
``` ```
......
...@@ -58,6 +58,47 @@ ...@@ -58,6 +58,47 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
string fractionToDecimal(int numerator, int denominator)
{
if (denominator == 0)
return "";
string ans;
if ((numerator > 0 && denominator < 0) || (numerator < 0 && denominator > 0))
ans = "-";
long long num = abs(static_cast<long long>(numerator));
long long den = abs(static_cast<long long>(denominator));
long long quo = num / den;
long long rem = num % den;
ans = ans + to_string(quo);
if (!rem)
return ans;
ans += ".";
unordered_map<long long, int> u_m;
string s = "";
int pos = 0;
while (rem)
{
if (u_m.find(rem) != u_m.end())
{
s.insert(u_m[rem], "(");
s += ")";
return ans + s;
}
u_m[rem] = pos++;
s += to_string((rem * 10) / den);
rem = (rem * 10) % den;
}
return ans + s;
}
};
``` ```
......
...@@ -61,6 +61,61 @@ bSTIterator.hasNext(); // 返回 False ...@@ -61,6 +61,61 @@ bSTIterator.hasNext(); // 返回 False
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class BSTIterator
{
public:
BSTIterator(TreeNode *root)
{
for (; root != nullptr; root = root->left)
{
sti_.push(root);
}
}
/** @return the next smallest number */
int next()
{
TreeNode *smallest = sti_.top();
sti_.pop();
int val = smallest->val;
smallest = smallest->right;
for (; smallest != nullptr; smallest = smallest->left)
{
sti_.push(smallest);
}
return val;
}
/** @return whether we have a next smallest number */
bool hasNext()
{
return !sti_.empty();
}
private:
stack<TreeNode *> sti_;
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
``` ```
......
# 第N高的薪水
<p>编写一个 SQL 查询,获取 <code>Employee</code> 表中第&nbsp;<em>n&nbsp;</em>高的薪水(Salary)。</p>
<pre>+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
</pre>
<p>例如上述&nbsp;<code>Employee</code>&nbsp;表,<em>n = 2&nbsp;</em>时,应返回第二高的薪水&nbsp;<code>200</code>。如果不存在第&nbsp;<em>n&nbsp;</em>高的薪水,那么查询应返回&nbsp;<code>null</code></p>
<pre>+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200 |
+------------------------+
</pre>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-244566ecbe2e4102870b2c5226713404",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "50b3ae039f7b4139bb60e7acba009381",
"author": "csdn.net",
"keywords": "数据库"
}
\ No newline at end of file
# 分数排名
<p>编写一个 SQL 查询来实现分数排名。</p>
<p>如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有&ldquo;间隔&rdquo;</p>
<pre>+----+-------+
| Id | Score |
+----+-------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+----+-------+
</pre>
<p>例如,根据上述给定的&nbsp;<code>Scores</code> 表,你的查询应该返回(按分数从高到低排列):</p>
<pre>+-------+------+
| Score | Rank |
+-------+------+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
|&nbsp;3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
+-------+------+
</pre>
<p><strong>重要提示:</strong>对于 MySQL 解决方案,如果要转义用作列名的保留字,可以在关键字之前和之后使用撇号。例如 <strong>`Rank`</strong></p>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -46,7 +46,43 @@ ...@@ -46,7 +46,43 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
bool compare(string a, string b)
{
string s1 = a + b;
string s2 = b + a;
return s1 > s2;
}
class Solution
{
public:
string largestNumber(vector<int> &nums)
{
string res = "";
int n = nums.size();
vector<string> tmp;
for (int i = 0; i < n; i++)
{
tmp.push_back(to_string(nums[i]));
}
sort(tmp.begin(), tmp.end(), compare);
for (int i = 0; i < tmp.size(); i++)
{
res += tmp[i];
}
if ('0' == res[0])
{
return "0";
}
else
{
return res;
}
}
};
``` ```
......
{
"node_id": "dailycode-950af1c37af24bc284565acce90e2a66",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "244a40cf4e234089b4307d8c8350ba78",
"author": "csdn.net",
"keywords": "数据库"
}
\ No newline at end of file
# 连续出现的数字
<p>表:<code>Logs</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| num | varchar |
+-------------+---------+
id 是这个表的主键。</pre>
<p> </p>
<p>编写一个 SQL 查询,查找所有至少连续出现三次的数字。</p>
<p>返回的结果表中的数据可以按 <strong>任意顺序</strong> 排列。</p>
<p> </p>
<p>查询结果格式如下面的例子所示:</p>
<p> </p>
<pre>
Logs 表:
+----+-----+
| Id | Num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+
Result 表:
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1 |
+-----------------+
1 是唯一连续出现至少三次的数字。
</pre>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-32c0f5429f2540e79a0e76bec87fb9bc",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "5a1946c07e994950b3cf62e8cf16a1be",
"author": "csdn.net",
"keywords": "数据库"
}
\ No newline at end of file
# 部门工资最高的员工
<p><code>Employee</code> 表包含所有员工信息,每个员工有其对应的&nbsp;Id, salary 和 department Id。</p>
<pre>+----+-------+--------+--------------+
| Id | Name | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 &nbsp;| Jim &nbsp; | 90000 &nbsp;| 1 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|
| 3 | Henry | 80000 | 2 |
| 4 | Sam | 60000 | 2 |
| 5 | Max | 90000 | 1 |
+----+-------+--------+--------------+</pre>
<p><code>Department</code>&nbsp;表包含公司所有部门的信息。</p>
<pre>+----+----------+
| Id | Name |
+----+----------+
| 1 | IT |
| 2 | Sales |
+----+----------+</pre>
<p>编写一个 SQL 查询,找出每个部门工资最高的员工。对于上述表,您的 SQL 查询应返回以下行(行的顺序无关紧要)。</p>
<pre>+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| IT &nbsp; &nbsp; &nbsp; &nbsp; | Jim &nbsp; &nbsp; &nbsp;| 90000 &nbsp;|
| Sales | Henry | 80000 |
+------------+----------+--------+</pre>
<p><strong>解释:</strong></p>
<p>Max 和 Jim 在 IT 部门的工资都是最高的,Henry 在销售部的工资最高。</p>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-213eff6cd62c47e5b35ee411403b2a99",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "fbed10f1207f4794b8841fc0b9b94e32",
"author": "csdn.net",
"keywords": "双指针,字符串"
}
\ No newline at end of file
# 翻转字符串里的单词 II
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -33,6 +33,39 @@ ...@@ -33,6 +33,39 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<string> findRepeatedDnaSequences(string s)
{
std::map<std::string, int> word_map;
std::vector<std::string> result;
for (int i = 0; i < s.length(); i++)
{
std::string word = s.substr(i, 10);
if (word_map.find(word) != word_map.end())
{
word_map[word] += 1;
}
else
{
word_map[word] = 1;
}
}
std::map<std::string, int>::iterator it;
for (it = word_map.begin(); it != word_map.end(); it++)
{
if (it->second > 1)
{
result.push_back(it->first);
}
}
return result;
}
};
``` ```
......
...@@ -50,6 +50,31 @@ ...@@ -50,6 +50,31 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
void rotate(vector<int> &nums, int k)
{
if (nums.empty())
{
return;
}
int length = nums.size();
k %= length;
while (k--)
{
int temp = nums[length - 1];
for (int i = length - 1; i > 0; i--)
{
nums[i] = nums[i - 1];
}
nums[0] = temp;
}
}
};
``` ```
......
{
"node_id": "dailycode-b31dab96ba6446e093f8d41c799f136e",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "2e404cdc85f148138041d73ed13ef5a3",
"author": "csdn.net",
"keywords": "位运算"
}
\ No newline at end of file
# 统计词频
<p>写一个 bash 脚本以统计一个文本文件&nbsp;<code>words.txt</code>&nbsp;中每个单词出现的频率。</p>
<p>为了简单起见,你可以假设:</p>
<ul>
<li><code>words.txt</code>只包括小写字母和&nbsp;<code>&#39; &#39;</code>&nbsp;</li>
<li>每个单词只由小写字母组成。</li>
<li>单词间由一个或多个空格字符分隔。</li>
</ul>
<p><strong>示例:</strong></p>
<p>假设 <code>words.txt</code> 内容如下:</p>
<pre>the day is sunny the the
the sunny is is
</pre>
<p>你的脚本应当输出(以词频降序排列):</p>
<pre>the 4
is 3
sunny 2
day 1
</pre>
<p><strong>说明:</strong></p>
<ul>
<li>不要担心词频相同的单词的排序问题,每个单词出现的频率都是唯一的。</li>
<li>你可以使用一行&nbsp;<a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-4.html">Unix pipes</a>&nbsp;实现吗?</li>
</ul>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-73e6df452f8f4416bce3c1244c071318",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "0be18e941d004a0b86d7c65ed0ef6539",
"author": "csdn.net",
"keywords": "shell"
}
\ No newline at end of file
# 转置文件
<p>给定一个文件 <code>file.txt</code>,转置它的内容。</p>
<p>你可以假设每行列数相同,并且每个字段由 <code>' '</code> 分隔。</p>
<p> </p>
<p><strong>示例:</strong></p>
<p>假设 <code>file.txt</code> 文件内容如下:</p>
<pre>
name age
alice 21
ryan 30
</pre>
<p>应当输出:</p>
<pre>
name alice ryan
age 21 30
</pre>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -36,6 +36,30 @@ ...@@ -36,6 +36,30 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int rob(vector<int> &nums)
{
int n = nums.size();
if (n == 0)
{
return 0;
}
vector<long> f(n + 1);
f[1] = nums[0];
for (int i = 2; i <= n; ++i)
{
f[i] = max(f[i - 1], f[i - 2] + nums[i - 1]);
}
return f[n];
}
};
``` ```
......
...@@ -40,7 +40,52 @@ ...@@ -40,7 +40,52 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<int> rightSideView(TreeNode *root)
{
vector<int> ret;
queue<TreeNode *> queues[2];
if (root != NULL)
queues[0].push(root);
int i = 0, j = 1, tmp;
TreeNode *p;
while (!queues[0].empty() || !queues[1].empty())
{
while (!queues[i].empty())
{
p = queues[i].front();
queues[i].pop();
if (p->left)
queues[j].push(p->left);
if (p->right)
queues[j].push(p->right);
tmp = p->val;
}
ret.push_back(tmp);
i = (i + 1) % 2;
j = (j + 1) % 2;
}
return ret;
}
};
``` ```
......
...@@ -47,7 +47,57 @@ ...@@ -47,7 +47,57 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
void DFS(vector<vector<int>> &mark, vector<vector<char>> &grid, int x, int y)
{
mark[x][y] = 1;
static const int dx[] = {-1, 1, 0, 0};
static const int dy[] = {0, 0, -1, 1};
for (int i = 0; i < 4; i++)
{
int newx = dx[i] + x;
int newy = dy[i] + y;
if (newx < 0 || newx >= mark.size() || newy < 0 || newy >= mark[newx].size())
{
continue;
}
if (mark[newx][newy] == 0 && grid[newx][newy] == '1')
{
DFS(mark, grid, newx, newy);
}
}
}
int numIslands(vector<vector<char>> &grid)
{
int island_num = 0;
vector<vector<int>> mark;
for (int i = 0; i < grid.size(); i++)
{
mark.push_back(vector<int>());
for (int j = 0; j < grid[i].size(); j++)
{
mark[i].push_back(0);
}
}
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[i].size(); j++)
{
if (mark[i][j] == 0 && grid[i][j] == '1')
{
DFS(mark, grid, i, j);
island_num++;
}
}
}
return island_num;
}
};
``` ```
......
...@@ -46,7 +46,29 @@ ...@@ -46,7 +46,29 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int numDistinct(string s, string t)
{
long dp[t.size() + 1][s.size() + 1];
for (int i = 0; i <= s.size(); ++i)
dp[0][i] = 1;
for (int i = 1; i <= t.size(); ++i)
dp[i][0] = 0;
for (int i = 1; i <= t.size(); ++i)
{
for (int j = 1; j <= s.size(); ++j)
{
dp[i][j] = dp[i][j - 1] + (t[i - 1] == s[j - 1] ? dp[i - 1][j - 1] : 0);
}
}
return dp[t.size()][s.size()];
}
};
``` ```
......
...@@ -54,7 +54,40 @@ ...@@ -54,7 +54,40 @@
```cpp ```cpp
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
int length = prices.size();
if (length < 2)
{
return 0;
}
vector<int> former(length, 0);
vector<int> later(length, 0);
int curMin = prices[0];
int curProfit = 0;
for (int i = 1; i < length; i++)
{
curProfit = max(curProfit, prices[i] - curMin);
curMin = min(curMin, prices[i]);
former[i] = curProfit;
}
int curMax = prices[length - 1];
curProfit = 0;
for (int i = length - 2; i >= 0; i--)
{
curProfit = max(curProfit, curMax - prices[i]);
curMax = max(curMax, prices[i]);
later[i] = curProfit;
}
int maxProfit = 0;
for (int i = 0; i < length; i++)
maxProfit = max(maxProfit, former[i] + later[i]);
return maxProfit;
}
};
``` ```
## 答案 ## 答案
......
...@@ -36,6 +36,69 @@ ...@@ -36,6 +36,69 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int maxPathSum(TreeNode *root)
{
if (!root)
return 0;
vector<TreeNode *> ss;
unordered_map<TreeNode *, int> val;
ss.push_back(root);
int len = 1;
queue<TreeNode *> q{{root}};
while (!q.empty())
{
TreeNode *t = q.front();
q.pop();
cout << t->val << endl;
if (t->left)
{
len++;
q.push(t->left);
ss.push_back(t->left);
}
if (t->right)
{
len++;
q.push(t->right);
ss.push_back(t->right);
}
}
int res = INT_MIN;
while (len > 0)
{
TreeNode *node = ss[--len];
int ps = node->val;
int s = ps;
int ls = max(0, val[node->left]);
int rs = max(0, val[node->right]);
ps += max(ls, rs);
val[node] = ps;
s += ls + rs;
res = max(s, res);
}
return res;
}
};
``` ```
......
...@@ -52,7 +52,77 @@ ...@@ -52,7 +52,77 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool differ_one(string &s, string &t)
{
int n = 0;
for (int i = 0; i < s.size(); ++i)
if ((n += s[i] != t[i]) > 1)
return false;
return n == 1;
}
vector<vector<int>> fa;
vector<string> tmp;
vector<vector<string>> ans;
void dfs(int index, vector<string> &wordList)
{
if (fa[index].empty())
{
reverse(tmp.begin(), tmp.end());
ans.push_back(tmp);
reverse(tmp.begin(), tmp.end());
}
for (auto &x : fa[index])
{
tmp.push_back(wordList[x]);
dfs(x, wordList);
tmp.pop_back();
}
}
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string> &wordList)
{
int b = -1, e = -1, x;
for (int i = 0; i < wordList.size(); ++i)
{
if (wordList[i] == beginWord)
b = i;
if (wordList[i] == endWord)
e = i;
}
if (e == -1)
return ans;
if (b == -1)
wordList.push_back(beginWord), b = wordList.size() - 1;
queue<int> que;
fa.assign(wordList.size(), vector<int>());
vector<int> index(wordList.size(), 0);
que.push(b), index[b] = 1;
while (!que.empty())
{
x = que.front(), que.pop();
if (index[e] && index[x] >= index[e])
break;
for (int i = 0; i < wordList.size(); ++i)
if ((index[i] == 0 || index[x] + 1 == index[i]) && differ_one(wordList[x], wordList[i]))
if (index[i] == 0)
index[i] = index[x] + 1, que.push(i), fa[i].push_back(x);
else
fa[i].push_back(x);
}
if (index[e] == 0)
return ans;
tmp.push_back(endWord);
dfs(e, wordList);
tmp.pop_back();
return ans;
}
};
``` ```
......
...@@ -45,6 +45,59 @@ ...@@ -45,6 +45,59 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int ladderLength(string beginWord, string endWord, vector<string> &wordList)
{
unordered_set<string> dict(wordList.begin(), wordList.end());
if (dict.find(endWord) == dict.end())
return 0;
queue<pair<string, int>> q;
q.push(make_pair(beginWord, 1));
string tmp;
int step;
while (!q.empty())
{
auto p = q.front();
if (p.first == endWord)
return p.second;
tmp = p.first;
step = p.second;
q.pop();
char old_ch;
for (int i = 0; i < tmp.size(); ++i)
{
old_ch = tmp[i];
for (char c = 'a'; c <= 'z'; ++c)
{
if (c == old_ch)
continue;
tmp[i] = c;
if (dict.find(tmp) != dict.end())
{
q.push(make_pair(tmp, step + 1));
dict.erase(tmp);
}
}
tmp[i] = old_ch;
}
}
return 0;
}
};
``` ```
......
...@@ -45,7 +45,44 @@ ...@@ -45,7 +45,44 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int minCut(string s)
{
const int N = s.size();
if (N <= 1)
return 0;
int i, j;
bool isPalin[N][N];
fill_n(&isPalin[0][0], N * N, false);
int minCuts[N + 1];
for (i = 0; i <= N; ++i)
minCuts[i] = i - 1;
for (j = 1; j < N; ++j)
{
for (i = j; i >= 0; --i)
{
if ((s[i] == s[j]) && ((j - i < 2) || isPalin[i + 1][j - 1]))
{
isPalin[i][j] = true;
minCuts[j + 1] = min(minCuts[j + 1], 1 + minCuts[i]);
}
}
}
return minCuts[N];
}
};
``` ```
......
...@@ -33,7 +33,36 @@ ...@@ -33,7 +33,36 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int candy(vector<int> &ratings)
{
int len = ratings.size();
if (len < 2)
return len;
int candy[len + 1];
candy[0] = 1;
for (int i = 1; i < len; i++)
{
if (ratings[i] > ratings[i - 1])
candy[i] = candy[i - 1] + 1;
else
candy[i] = 1;
}
int ans = 0;
for (int i = len - 1; i > 0; i--)
{
if (candy[i] >= candy[i - 1] && ratings[i] < ratings[i - 1])
candy[i - 1] = max(candy[i - 1], candy[i] + 1);
ans += candy[i];
}
return ans + candy[0];
}
};
``` ```
......
...@@ -48,7 +48,57 @@ wordDict = [&quot;cats&quot;, &quot;dog&quot;, &quot;sand&quot;, &quot;and&quot; ...@@ -48,7 +48,57 @@ wordDict = [&quot;cats&quot;, &quot;dog&quot;, &quot;sand&quot;, &quot;and&quot;
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<string> res;
unordered_set<string> wordset;
unordered_set<int> lenset;
vector<string> wordBreak(string s, vector<string> &wordDict)
{
for (const auto &w : wordDict)
{
wordset.insert(w);
lenset.insert(w.size());
}
vector<int> dp(s.size() + 1, 0);
dp[0] = 1;
for (int i = 1; i <= s.size(); ++i)
{
for (const auto &j : lenset)
{
if (i >= j && dp[i - j] && wordset.count(s.substr(i - j, j)))
dp[i] = 1;
}
}
if (dp.back() == 0)
return res;
backtrack(dp, 0, s, "");
return res;
}
void backtrack(vector<int> &dp, int idx, string &s, string tmp)
{
if (idx == s.size())
{
tmp.pop_back();
res.push_back(tmp);
return;
}
for (int i = idx + 1; i < dp.size(); ++i)
{
if (dp[i] == 1 && wordset.count(s.substr(idx, i - idx)))
{
backtrack(dp, i, s, tmp + s.substr(idx, i - idx) + " ");
}
}
}
};
``` ```
......
...@@ -33,6 +33,52 @@ ...@@ -33,6 +33,52 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct Point
{
int x;
int y;
Point() : x(0), y(0) {}
Point(int a, int b) : x(a), y(b) {}
};
class Solution
{
public:
int maxPoints(vector<Point> &points)
{
int ans = 0;
for (int i = 0; i < points.size(); ++i)
{
map<pair<int, int>, int> m;
int p = 1;
for (int j = i + 1; j < points.size(); ++j)
{
if (points[i].x == points[j].x && (points[i].y == points[j].y))
{
++p;
continue;
}
int dx = points[j].x - points[i].x;
int dy = points[j].y - points[i].y;
int d = gcd(dx, dy);
++m[{dx / d, dy / d}];
}
ans = max(ans, p);
for (auto it = m.begin(); it != m.end(); ++it)
{
ans = max(ans, it->second + p);
}
}
return ans;
}
int gcd(int a, int b)
{
return (b == 0) ? a : gcd(b, a % b);
}
};
``` ```
......
...@@ -51,7 +51,29 @@ ...@@ -51,7 +51,29 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int findMin(vector<int> &nums)
{
int left = 0, right = nums.size() - 1;
while (left < right)
{
int mid = left + (right - left) / 2;
if (nums[mid] < nums[right])
right = mid;
else if (nums[mid] > nums[right])
left = mid + 1;
else if (nums[mid] == nums[right])
right--;
}
return nums[right];
}
};
``` ```
## 答案 ## 答案
......
{
"node_id": "dailycode-49f201d5e01144c2a2f84579429f836c",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "b2aa3694ca0242de826c70ff63223507",
"author": "csdn.net",
"keywords": "字符串,交互,模拟"
}
\ No newline at end of file
# 用 Read4 读取 N 个字符 II
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -27,7 +27,32 @@ ...@@ -27,7 +27,32 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maximumGap(vector<int> &nums)
{
set<int> st(nums.begin(), nums.end());
int res = 0, pre = INT_MIN;
for (auto iter = st.begin(); iter != st.end(); ++iter)
{
if (pre == INT_MIN)
{
pre = *iter;
continue;
}
else
{
res = max(res, *iter - pre);
pre = *iter;
}
}
return res;
}
};
``` ```
......
...@@ -62,7 +62,37 @@ table.dungeon, .dungeon th, .dungeon td { ...@@ -62,7 +62,37 @@ table.dungeon, .dungeon th, .dungeon td {
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int calculateMinimumHP(vector<vector<int>> &dungeon)
{
int row = dungeon.size();
int col = dungeon[0].size();
int dp[row][col] = {0};
dp[row - 1][col - 1] = max(1 - dungeon[row - 1][col - 1], 1);
for (int i = row - 2; i >= 0; i--)
{
dp[i][col - 1] = max(dp[i + 1][col - 1] - dungeon[i][col - 1], 1);
}
for (int i = col - 2; i >= 0; i--)
{
dp[row - 1][i] = max(dp[row - 1][i + 1] - dungeon[row - 1][i], 1);
}
for (int i = row - 2; i >= 0; i--)
{
for (int j = col - 2; j >= 0; j--)
{
dp[i][j] = max(min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j], 1);
}
}
return dp[0][0];
}
};
``` ```
## 答案 ## 答案
......
{
"node_id": "dailycode-c8cd86452f7b48b1a1a34c7f9848eac0",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "6d285794dd484abdb77537828c8b39d0",
"author": "csdn.net",
"keywords": "数据库"
}
\ No newline at end of file
# 部门工资前三高的所有员工
<p><code>Employee</code> 表包含所有员工信息,每个员工有其对应的工号&nbsp;<code>Id</code>,姓名 <code>Name</code>,工资 <code>Salary</code> 和部门编号 <code>DepartmentId</code></p>
<pre>+----+-------+--------+--------------+
| Id | Name | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1 | Joe | 85000 | 1 |
| 2 | Henry | 80000 | 2 |
| 3 | Sam | 60000 | 2 |
| 4 | Max | 90000 | 1 |
| 5 | Janet | 69000 | 1 |
| 6 | Randy | 85000 | 1 |
| 7 | Will | 70000 | 1 |
+----+-------+--------+--------------+</pre>
<p><code>Department</code> 表包含公司所有部门的信息。</p>
<pre>+----+----------+
| Id | Name |
+----+----------+
| 1 | IT |
| 2 | Sales |
+----+----------+</pre>
<p>编写一个&nbsp;SQL 查询,找出每个部门获得前三高工资的所有员工。例如,根据上述给定的表,查询结果应返回:</p>
<pre>+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| IT | Randy | 85000 |
| IT | Joe | 85000 |
| IT | Will | 70000 |
| Sales | Henry | 80000 |
| Sales | Sam | 60000 |
+------------+----------+--------+</pre>
<p><strong>解释:</strong></p>
<p>IT 部门中,Max 获得了最高的工资,Randy 和 Joe 都拿到了第二高的工资,Will 的工资排第三。销售部门(Sales)只有两名员工,Henry 的工资最高,Sam 的工资排第二。</p>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -38,7 +38,40 @@ ...@@ -38,7 +38,40 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxProfit(int k, vector<int> &prices)
{
const int len = prices.size();
if (len <= 1 || k == 0)
return 0;
if (k > len / 2)
k = len / 2;
const int count = k;
int buy[count];
int sell[count];
for (int i = 0; i < count; ++i)
{
buy[i] = -prices[0];
sell[i] = 0;
}
for (int i = 1; i < len; ++i)
{
buy[0] = max(buy[0], -prices[i]);
sell[0] = max(sell[0], buy[0] + prices[i]);
for (int j = count - 1; j > 0; --j)
{
buy[j] = max(buy[j], sell[j - 1] - prices[i]);
sell[j] = max(buy[j] + prices[i], sell[j]);
}
}
return sell[count - 1];
}
};
``` ```
## 答案 ## 答案
......
...@@ -39,6 +39,95 @@ ...@@ -39,6 +39,95 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
struct Node
{
bool isflag = false;
Node *next[27] = {};
};
set<string> res;
vector<string> ans;
Node *root;
vector<int> dirx{0, 0, 1, -1};
vector<int> diry{1, -1, 0, 0};
bool flag;
void createtree(vector<string> &words)
{
root = new Node();
for (auto w : words)
{
Node *p = root;
for (int i = 0; i < w.length(); i++)
{
if (p->next[w[i] - 'a'] == NULL)
{
p->next[w[i] - 'a'] = new Node();
}
p = p->next[w[i] - 'a'];
}
p->isflag = true;
}
}
void backtrack(vector<vector<char>> &board, vector<vector<bool>> visited, int row, int col, Node *roott, string cur)
{
cur += board[row][col];
roott = roott->next[board[row][col] - 'a'];
if (!roott)
return;
if (roott->isflag == true)
{
res.insert(cur);
flag = true;
}
visited[row][col] = true;
for (int i = 0; i < 4; i++)
{
int nx = row + dirx[i];
int ny = col + diry[i];
if (nx < 0 || ny < 0 || nx >= board.size() || ny >= board[0].size())
continue;
if (visited[nx][ny] == false)
{
backtrack(board, visited, nx, ny, roott, cur);
}
}
}
vector<string> findWords(vector<vector<char>> &board, vector<string> &words)
{
if (board.size() == 0 || words.size() == 0)
return ans;
createtree(words);
for (int i = 0; i < board.size(); i++)
{
for (int j = 0; j < board[i].size(); j++)
{
Node *p = root;
flag = false;
if (p->next[board[i][j] - 'a'])
{
vector<vector<bool>> visited{board.size(), vector<bool>(board[0].size(), false)};
backtrack(board, visited, i, j, p, "");
}
}
}
set<string>::iterator it;
for (it = res.begin(); it != res.end(); it++)
ans.push_back(*it);
return ans;
}
};
``` ```
......
...@@ -31,6 +31,58 @@ ...@@ -31,6 +31,58 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
string shortestPalindrome(string s)
{
string rev(s);
reverse(rev.begin(), rev.end());
;
string combine = s + "#" + rev;
vector<int> lps(combine.length(), 0);
int remove = getLPS(combine, lps);
string prepend = rev.substr(0, rev.length() - remove);
return prepend + s;
}
int getLPS(string s, vector<int> &lps)
{
int j = 0, i = 1;
while (i < s.length())
{
if (s[i] == s[j])
{
lps[i] = j + 1;
i++;
j++;
}
else
{
if (j != 0)
{
j = lps[j - 1];
}
else
{
lps[i] = 0;
i++;
}
}
}
return lps[lps.size() - 1];
}
};
``` ```
......
...@@ -47,7 +47,40 @@ ...@@ -47,7 +47,40 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<pair<int, int>> getSkyline(vector<vector<int>> &buildings)
{
vector<pair<int, int>> h, res;
multiset<int> m;
int pre = 0, cur = 0;
for (auto &a : buildings)
{
h.push_back({a[0], -a[2]});
h.push_back({a[1], a[2]});
}
sort(h.begin(), h.end());
m.insert(0);
for (auto &a : h)
{
if (a.second < 0)
m.insert(-a.second);
else
m.erase(m.find(a.second));
cur = *m.rbegin();
if (cur != pre)
{
res.push_back({a.first, cur});
pre = cur;
}
}
return res;
}
};
``` ```
......
...@@ -39,7 +39,86 @@ ...@@ -39,7 +39,86 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int calculate(string s)
{
stack<int> myStack;
stack<char> myOperator;
int i;
for (i = 0; i < s.length(); i++)
{
while (i < s.length() && s[i] == ' ')
i++;
if (i == s.length())
break;
if (s[i] == '+' || s[i] == '-' || s[i] == '(')
myOperator.push(s[i]);
else if (s[i] == ')')
{
while (myOperator.top() != '(')
{
int element1 = myStack.top();
myStack.pop();
int element2 = myStack.top();
myStack.pop();
char op = myOperator.top();
myOperator.pop();
if (op == '+')
myStack.push(element1 + element2);
else if (op == '-')
myStack.push(element2 - element1);
}
if (!myOperator.empty())
myOperator.pop();
while (!myOperator.empty() && (myOperator.top() != '('))
{
int element1 = myStack.top();
myStack.pop();
int element2 = myStack.top();
myStack.pop();
char op = myOperator.top();
myOperator.pop();
if (op == '+')
myStack.push(element1 + element2);
else if (op == '-')
myStack.push(element2 - element1);
}
}
else
{
long long int number = 0;
int j = i;
while (j < s.length() && (s[j] - '0' <= 9) && (s[j] - '0' >= 0))
{
number = number * 10 + (s[j] - '0');
j++;
}
i = j - 1;
myStack.push(number);
while (!myOperator.empty() && (myOperator.top() != '('))
{
int element1 = myStack.top();
myStack.pop();
int element2 = myStack.top();
myStack.pop();
char op = myOperator.top();
myOperator.pop();
if (op == '+')
myStack.push(element1 + element2);
else if (op == '-')
myStack.push(element2 - element1);
}
}
}
return myStack.top();
}
};
``` ```
......
...@@ -30,6 +30,25 @@ ...@@ -30,6 +30,25 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int countDigitOne(int n)
{
int cnt = 0;
for (long int i = 1; i <= n; i *= 10)
{
int a = n / i, b = n % i;
cnt += (a + 8) / 10 * i + (a % 10 == 1) * (b + 1);
if (i == 1000000000)
break;
}
return cnt;
}
};
``` ```
......
...@@ -63,6 +63,35 @@ ...@@ -63,6 +63,35 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k)
{
vector<int> ans;
int n = nums.size();
if (n == 0 || k > n)
return ans;
deque<int> que;
for (int i = 0; i < n; i++)
{
if (!que.empty())
{
if (i >= que.front() + k)
que.pop_front();
while (!que.empty() && nums[i] >= nums[que.back()])
que.pop_back();
}
que.push_back(i);
if (i + 1 >= k)
ans.push_back(nums[que.front()]);
}
return ans;
}
};
``` ```
......
{
"node_id": "dailycode-628335996f8841539f799aa4e7a9f566",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "fe40de84da824faab29335d99ba2e657",
"author": "csdn.net",
"keywords": "递归,数组,字符串"
}
\ No newline at end of file
# 中心对称数 III
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-074590fe6aba43c38069b88da114d531",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "60abd10c9b734a86b65145f3247c8099",
"author": "csdn.net",
"keywords": "数据库"
}
\ No newline at end of file
# 行程和用户
表:<code>Trips</code>
<div class="original__bRMd">
<div>
<pre>
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| Id | int |
| Client_Id | int |
| Driver_Id | int |
| City_Id | int |
| Status | enum |
| Request_at | date |
+-------------+----------+
Id 是这张表的主键。
这张表中存所有出租车的行程信息。每段行程有唯一 Id ,其中 Client_Id 和 Driver_Id 是 Users 表中 Users_Id 的外键。
Status 是一个表示行程状态的枚举类型,枚举成员为(‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’) 。
</pre>
<p> </p>
<div class="original__bRMd">
<div>
<p>表:<code>Users</code></p>
</div>
</div>
<pre>
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| Users_Id | int |
| Banned | enum |
| Role | enum |
+-------------+----------+
Users_Id 是这张表的主键。
这张表中存所有用户,每个用户都有一个唯一的 Users_Id ,Role 是一个表示用户身份的枚举类型,枚举成员为 (‘client’, ‘driver’, ‘partner’) 。
Banned 是一个表示用户是否被禁止的枚举类型,枚举成员为 (‘Yes’, ‘No’) 。
</pre>
<p> </p>
<p>写一段 SQL 语句查出 <code>"2013-10-01"</code><strong> </strong>至 <code>"2013-10-03"</code><strong> </strong>期间非禁止用户(<strong>乘客和司机都必须未被禁止</strong>)的取消率。非禁止用户即 Banned 为 No 的用户,禁止用户即 Banned 为 Yes 的用户。</p>
<p><strong>取消率</strong> 的计算方式如下:(被司机或乘客取消的非禁止用户生成的订单数量) / (非禁止用户生成的订单总数)。</p>
<p>返回结果表中的数据可以按任意顺序组织。其中取消率 <code>Cancellation Rate</code> 需要四舍五入保留 <strong>两位小数</strong></p>
<p> </p>
<p>查询结果格式如下例所示:</p>
<pre>
Trips 表:
+----+-----------+-----------+---------+---------------------+------------+
| Id | Client_Id | Driver_Id | City_Id | Status | Request_at |
+----+-----------+-----------+---------+---------------------+------------+
| 1 | 1 | 10 | 1 | completed | 2013-10-01 |
| 2 | 2 | 11 | 1 | cancelled_by_driver | 2013-10-01 |
| 3 | 3 | 12 | 6 | completed | 2013-10-01 |
| 4 | 4 | 13 | 6 | cancelled_by_client | 2013-10-01 |
| 5 | 1 | 10 | 1 | completed | 2013-10-02 |
| 6 | 2 | 11 | 6 | completed | 2013-10-02 |
| 7 | 3 | 12 | 6 | completed | 2013-10-02 |
| 8 | 2 | 12 | 12 | completed | 2013-10-03 |
| 9 | 3 | 10 | 12 | completed | 2013-10-03 |
| 10 | 4 | 13 | 12 | cancelled_by_driver | 2013-10-03 |
+----+-----------+-----------+---------+---------------------+------------+
Users 表:
+----------+--------+--------+
| Users_Id | Banned | Role |
+----------+--------+--------+
| 1 | No | client |
| 2 | Yes | client |
| 3 | No | client |
| 4 | No | client |
| 10 | No | driver |
| 11 | No | driver |
| 12 | No | driver |
| 13 | No | driver |
+----------+--------+--------+
Result 表:
+------------+-------------------+
| Day | Cancellation Rate |
+------------+-------------------+
| 2013-10-01 | 0.33 |
| 2013-10-02 | 0.00 |
| 2013-10-03 | 0.50 |
+------------+-------------------+
2013-10-01:
- 共有 4 条请求,其中 2 条取消。
- 然而,Id=2 的请求是由禁止用户(User_Id=2)发出的,所以计算时应当忽略它。
- 因此,总共有 3 条非禁止请求参与计算,其中 1 条取消。
- 取消率为 (1 / 3) = 0.33
2013-10-02:
- 共有 3 条请求,其中 0 条取消。
- 然而,Id=6 的请求是由禁止用户发出的,所以计算时应当忽略它。
- 因此,总共有 2 条非禁止请求参与计算,其中 0 条取消。
- 取消率为 (0 / 2) = 0.00
2013-10-03:
- 共有 3 条请求,其中 1 条取消。
- 然而,Id=8 的请求是由禁止用户发出的,所以计算时应当忽略它。
- 因此,总共有 2 条非禁止请求参与计算,其中 1 条取消。
- 取消率为 (1 / 2) = 0.50
</pre>
</div>
</div>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-9f00778149124d1fb4fe252c56cb752d",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "fe307b22d8504239a26cd327d212c4ca",
"author": "csdn.net",
"keywords": "数组,动态规划"
}
\ No newline at end of file
# 粉刷房子 II
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-aa039e08044a46348cc5f4e989a03b85",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
# 火星词典
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-633c198f85454eefa51290efdf1fed95",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "291feb913dc349d2853e7eaeb74c6440",
"author": "csdn.net",
"keywords": "栈,树,深度优先搜索,二叉搜索树,双指针,二叉树,堆(优先队列)"
}
\ No newline at end of file
# 最接近的二叉搜索树值 II
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -44,7 +44,55 @@ ...@@ -44,7 +44,55 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
const int Mod[3] = {1000000000, 1000000, 1000};
string H[3] = {"Billion", "Million", "Thousand"},
M[8] = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"},
L[20] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
void update(string &ans)
{
ans += ans == "" ? "" : " ";
}
string numberToWords2(int num)
{
if (num < 20)
return L[num];
string ans;
if (num >= 100)
ans += L[num / 100] + " Hundred", num %= 100;
if (num == 0)
return ans;
else if (num < 20)
update(ans), ans += L[num];
else
{
update(ans), ans += M[num / 10 - 2], num %= 10;
if (num == 0)
return ans;
else
update(ans), ans += L[num];
}
return ans;
}
string numberToWords(int num)
{
if (num < 20)
return L[num];
string ans;
for (int i = 0; i < 3; ++i)
if (num >= Mod[i])
update(ans), ans += numberToWords2(num / Mod[i]) + " " + H[i], num %= Mod[i];
if (num)
update(ans), ans += numberToWords2(num);
return ans;
}
};
``` ```
......
...@@ -50,7 +50,40 @@ ...@@ -50,7 +50,40 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<string> addOperators(string num, int target)
{
vector<string> res;
addOperatorsDFS(num, target, 0, 0, "", res);
return res;
}
void addOperatorsDFS(string num, int target, long long diff, long long curNum, string out, vector<string> &res)
{
if (num.size() == 0 && curNum == target)
res.push_back(out);
for (int i = 1; i <= num.size(); ++i)
{
string cur = num.substr(0, i);
if (cur.size() > 1 && cur[0] == '0')
return;
string next = num.substr(i);
if (out.size() > 0)
{
addOperatorsDFS(next, target, stoll(cur), curNum + stoll(cur), out + "+" + cur, res);
addOperatorsDFS(next, target, -stoll(cur), curNum - stoll(cur), out + "-" + cur, res);
addOperatorsDFS(next, target, diff * stoll(cur), (curNum - diff) + diff * stoll(cur), out + "*" + cur, res);
}
else
addOperatorsDFS(next, target, stoll(cur), stoll(cur), cur, res);
}
}
};
``` ```
......
...@@ -34,7 +34,40 @@ findMedian() -&gt; 2</pre> ...@@ -34,7 +34,40 @@ findMedian() -&gt; 2</pre>
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class MedianFinder
{
public:
/** initialize your data structure here. */
MedianFinder()
{
}
void addNum(int num)
{
auto it = upper_bound(nums.begin(), nums.end(), num);
nums.insert(it, num);
}
double findMedian()
{
int n = nums.size();
if (n % 2 == 0)
return 1.0 * (nums[n / 2 - 1] + nums[n / 2]) / 2;
else
return nums[n / 2];
}
vector<int> nums;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/
``` ```
......
{
"node_id": "dailycode-d3dc18ee39d44a61aafd21f2fcba7193",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "512fdf0148974c72a98c33435828fc09",
"author": "csdn.net",
"keywords": "数组,数学,矩阵,排序"
}
\ No newline at end of file
# 最佳的碰头地点
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -49,7 +49,50 @@ ...@@ -49,7 +49,50 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Codec
{
public:
string serialize(TreeNode *root)
{
if (!root)
return "#_";
return to_string(root->val) + "_" + serialize(root->left) + serialize(root->right);
}
TreeNode *deserialize(string data)
{
cout << data << endl;
queue<string> q;
stringstream ss(data);
string s;
while (getline(ss, s, '_'))
q.push(s);
return help(q);
}
TreeNode *help(queue<string> &q)
{
auto cur = q.front();
q.pop();
if (cur == "#")
return NULL;
auto root = new TreeNode(stoi(cur));
root->left = help(q);
root->right = help(q);
return root;
}
};
``` ```
......
...@@ -41,6 +41,53 @@ ...@@ -41,6 +41,53 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<string> removeInvalidParentheses(string s)
{
vector<string> ans;
rm(move(s), ans, {'(', ')'}, 0, 0);
if (ans.empty())
return {""};
return ans;
}
void rm(string s, vector<string> &ans, vector<char> brackets, int sea_i, int del_i)
{
int sta = 0;
for (int i = sea_i; i < s.size(); i++)
{
if (s[i] == brackets[0])
sta++;
else if (s[i] == brackets[1])
{
sta--;
if (sta < 0)
{
for (int j = del_i; j <= i; j++)
{
if (s[j] == brackets[1] && (j == del_i || s[j - 1] != brackets[1]))
{
string new_s = s.substr(0, j) + s.substr(j + 1);
rm(move(new_s), ans, brackets, i, j);
}
}
return;
}
}
}
reverse(s.begin(), s.end());
if (brackets[0] == '(')
rm(move(s), ans, {brackets[1], brackets[0]}, 0, 0);
else
ans.push_back(move(s));
}
};
``` ```
......
{
"node_id": "dailycode-ee6d28c728da446281e36cce4f00d185",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "8e86497cc7714b4b97025466d96b6fc8",
"author": "csdn.net",
"keywords": "深度优先搜索,广度优先搜索,数组,二分查找,矩阵"
}
\ No newline at end of file
# 包含全部黑色像素的最小矩形
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-a0b6ba89feb84ddab4f88213e97b2db1",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "f8dd07bb72784c4d913949a13a6e2be0",
"author": "csdn.net",
"keywords": "并查集,数组"
}
\ No newline at end of file
# 岛屿数量 II
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-d2f2b1a20e0948aaac5e162103913570",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "12e2d537f6664ed8a3afbdbb1fb1c620",
"author": "csdn.net",
"keywords": "设计,树状数组,线段树,数组,矩阵"
}
\ No newline at end of file
# 二维区域和检索
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -37,7 +37,33 @@ coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167</pre> ...@@ -37,7 +37,33 @@ coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167</pre>
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxCoins(vector<int> &nums)
{
vector<int> dpnums(nums.size() + 2, 1);
for (int i = 0, j = 1; i < nums.size(); i++, j++)
dpnums[j] = nums[i];
vector<vector<int>> coins(dpnums.size(), vector<int>(dpnums.size(), 0));
for (int i = 2; i < dpnums.size(); i++)
{
for (int j = 0; j + i < dpnums.size(); j++)
{
for (int k = j + 1; k < j + i; k++)
{
coins[j][j + i] = max(coins[j][j + i], coins[j][k] + coins[k][j + i] +
dpnums[j] * dpnums[k] * dpnums[j + i]);
}
}
}
return coins[0][dpnums.size() - 1];
}
};
``` ```
......
...@@ -43,6 +43,73 @@ ...@@ -43,6 +43,73 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
struct BSTNode
{
int val;
int count;
BSTNode *left;
BSTNode *right;
BSTNode(int x) : val(x), left(NULL), right(NULL), count(0) {}
};
void BST_insert(BSTNode *node, BSTNode *insert_node, int &count_small)
{
if (insert_node->val <= node->val)
{
node->count++;
if (node->left)
{
BST_insert(node->left, insert_node, count_small);
}
else
{
node->left = insert_node;
}
}
else
{
count_small += node->count + 1;
if (node->right)
{
BST_insert(node->right, insert_node, count_small);
}
else
{
node->right = insert_node;
}
}
}
vector<int> countSmaller(vector<int> &nums)
{
vector<int> result;
vector<BSTNode *> node_vec;
vector<int> count;
for (int i = nums.size() - 1; i >= 0; i--)
{
node_vec.push_back(new BSTNode(nums[i]));
}
count.push_back(0);
for (int i = 1; i < node_vec.size(); i++)
{
int count_small = 0;
BST_insert(node_vec[0], node_vec[i], count_small);
count.push_back(count_small);
}
for (int i = node_vec.size() - 1; i >= 0; i--)
{
delete node_vec[i];
result.push_back(count[i]);
}
return result;
}
};
``` ```
......
{
"node_id": "dailycode-e9efbb273d38435e9dc8f37360a068b5",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "3a8c7a4666fd418197154af3534f1827",
"author": "csdn.net",
"keywords": "广度优先搜索,数组,矩阵"
}
\ No newline at end of file
# 离建筑物最近的距离
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -37,7 +37,64 @@ k = <code>3</code> ...@@ -37,7 +37,64 @@ k = <code>3</code>
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> maxNumber(vector<int> &nums1, vector<int> &nums2, int k)
{
vector<int> ans;
const int n1 = nums1.size();
const int n2 = nums2.size();
for (int k1 = 0; k1 <= k; ++k1)
{
const int k2 = k - k1;
if (k1 > n1 || k2 > n2)
{
continue;
}
ans = max(ans, maxNumber(maxNumber(nums1, k1), maxNumber(nums2, k2)));
}
return ans;
}
private:
vector<int> maxNumber(const vector<int> &nums, const int k)
{
if (k == 0)
{
return {};
}
vector<int> ans;
int to_pop = nums.size() - k;
for (const int num : nums)
{
while (!ans.empty() && num > ans.back() && to_pop-- > 0)
{
ans.pop_back();
}
ans.push_back(num);
}
ans.resize(k);
return ans;
}
vector<int> maxNumber(const vector<int> &nums1, const vector<int> &nums2)
{
vector<int> ans;
auto s1 = nums1.cbegin();
auto e1 = nums1.cend();
auto s2 = nums2.cbegin();
auto e2 = nums2.cend();
while (s1 != e1 || s2 != e2)
{
ans.push_back(lexicographical_compare(s1, e1, s2, e2) ? *s2++ : *s1++);
}
return ans;
}
};
``` ```
......
...@@ -35,6 +35,31 @@ ...@@ -35,6 +35,31 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int countRangeSum(vector<int> &nums, int lower, int upper)
{
int n = nums.size();
long presum = 0;
multiset<long> S;
S.insert(0);
int ret = 0;
for (int i = 0; i < n; i++)
{
presum += nums[i];
ret += distance(S.lower_bound(presum - upper), S.upper_bound(presum - lower));
S.insert(presum);
}
return ret;
}
};
``` ```
......
...@@ -43,6 +43,56 @@ ...@@ -43,6 +43,56 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
static constexpr int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int m, n;
int longestIncreasingPath(vector<vector<int>> &matrix)
{
if (matrix.size() == 0 || matrix[0].size() == 0)
{
return 0;
}
m = matrix.size();
n = matrix[0].size();
int res = 0;
auto memo = vector<vector<int>>(m, vector<int>(n, 0));
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (memo[i][j])
res = max(res, memo[i][j]);
else
res = max(res, dfs(i, j, matrix, memo));
}
}
return res;
}
int dfs(int i, int j, vector<vector<int>> &matrix, vector<vector<int>> &memo)
{
int temp = 1;
for (int k = 0; k < 4; ++k)
{
int x = i + dirs[k][0];
int y = j + dirs[k][1];
if ((x >= 0) && (x < m) && (y >= 0) && (y < n) && (matrix[i][j] < matrix[x][y]))
{
if (memo[x][y])
temp = max(temp, memo[x][y] + 1);
else
temp = max(temp, dfs(x, y, matrix, memo) + 1);
}
}
memo[i][j] = temp;
return temp;
}
};
``` ```
......
...@@ -29,6 +29,35 @@ ...@@ -29,6 +29,35 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int minPatches(vector<int> &nums, int n)
{
long max_sum = 0;
int m = nums.size();
int cnt = 0;
for (long i = 1, pos = 0; i <= n;)
{
if (pos >= m || i < nums[pos])
{
cnt++;
max_sum += i;
}
else
{
max_sum += nums[pos];
pos++;
}
i = max_sum + 1;
}
return cnt;
}
};
``` ```
......
...@@ -41,7 +41,36 @@ ...@@ -41,7 +41,36 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isSelfCrossing(vector<int> &distance)
{
int all_step = distance.size(), current_step = 0;
if (all_step < 4)
return false;
current_step = 2;
while (current_step < all_step && distance[current_step] > distance[current_step - 2])
current_step++;
if (current_step == all_step)
return false;
if (distance[current_step] >= distance[current_step - 2] - (current_step > 3 ? distance[current_step - 4] : 0))
distance[current_step - 1] -= current_step > 2 ? distance[current_step - 3] : 0;
current_step++;
while (current_step < all_step && distance[current_step] < distance[current_step - 2])
current_step++;
return current_step != all_step;
}
};
``` ```
......
...@@ -40,6 +40,57 @@ ...@@ -40,6 +40,57 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<vector<int>> palindromePairs(vector<string> &words)
{
vector<vector<int>> res;
unordered_map<string, int> m;
set<int> s;
for (int i = 0; i < words.size(); ++i)
{
m[words[i]] = i;
s.insert(words[i].size());
}
for (int i = 0; i < words.size(); ++i)
{
string t = words[i];
int len = t.size();
reverse(t.begin(), t.end());
if (m.count(t) && m[t] != i)
{
res.push_back({i, m[t]});
}
auto a = s.find(len);
for (auto it = s.begin(); it != a; ++it)
{
int d = *it;
if (isValid(t, 0, len - d - 1) && m.count(t.substr(len - d)))
{
res.push_back({i, m[t.substr(len - d)]});
}
if (isValid(t, d, len - 1) && m.count(t.substr(0, d)))
{
res.push_back({m[t.substr(0, d)], i});
}
}
}
return res;
}
bool isValid(string t, int left, int right)
{
while (left < right)
{
if (t[left++] != t[right--])
return false;
}
return true;
}
};
``` ```
......
...@@ -56,6 +56,91 @@ summaryRanges.getIntervals(); // 返回 [[1, 3], [6, 7]] ...@@ -56,6 +56,91 @@ summaryRanges.getIntervals(); // 返回 [[1, 3], [6, 7]]
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class SummaryRanges
{
public:
vector<vector<int>> ans;
unordered_map<int, int> use;
int size;
/** Initialize your data structure here. */
SummaryRanges()
{
size = 0;
}
void addNum(int val)
{
if (use.count(val) != 0)
return;
use[val] = 1;
int i;
for (i = 0; i < size; i++)
if (val < ans[i][0])
break;
if (i == 0)
{
if (size == 0)
{
ans.insert(ans.begin(), {val, val});
size++;
}
else if (val + 1 == ans[i][0])
ans[0][0] = val;
else
{
ans.insert(ans.begin(), {val, val});
size++;
}
}
else if (i == size)
{
if (val - 1 == ans[i - 1][1])
ans[i - 1][1] = val;
else
{
ans.push_back({val, val});
size++;
}
}
else
{
if (val + 1 != ans[i][0] && val - 1 != ans[i - 1][1])
{
ans.insert(ans.begin() + i, {val, val});
size++;
}
else if (val + 1 == ans[i][0] && val - 1 == ans[i - 1][1])
{
ans[i - 1][1] = ans[i][1];
ans.erase(ans.begin() + i);
size--;
}
else if (val + 1 == ans[i][0])
{
ans[i][0] = val;
}
else
{
ans[i - 1][1] = val;
}
}
}
vector<vector<int>> getIntervals()
{
return ans;
}
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges* obj = new SummaryRanges();
* obj->addNum(val);
* vector<vector<int>> param_2 = obj->getIntervals();
*/
``` ```
......
...@@ -37,7 +37,49 @@ ...@@ -37,7 +37,49 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxEnvelopes(vector<vector<int>> &envelopes)
{
sort(envelopes.begin(), envelopes.end(), comp);
vector<int> dp(envelopes.size(), 1);
for (int i = 0; i < envelopes.size(); ++i)
{
for (int j = 0; j < i; ++j)
{
if (envelopes[i][1] > envelopes[j][1])
dp[i] = dp[i] > dp[j] + 1 ? dp[i] : dp[j] + 1;
}
}
int res = 0;
for (int i = 0; i < dp.size(); ++i)
res = res > dp[i] ? res : dp[i];
return res;
}
static bool comp(const vector<int> &a, const vector<int> &b)
{
if (a[0] < b[0])
return true;
else if (a[0] > b[0])
return false;
else
{
if (a[1] > b[1])
return true;
else
return false;
}
}
};
``` ```
......
{
"node_id": "dailycode-ad9b15b133d24f708105a919c319fc22",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "a884968518654253a6f7d79946ef4351",
"author": "csdn.net",
"keywords": "贪心,哈希表,字符串,计数,排序,堆(优先队列)"
}
\ No newline at end of file
# K 距离间隔重排字符串
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -41,6 +41,46 @@ ...@@ -41,6 +41,46 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxSumSubmatrix(vector<vector<int>> &mat, int k)
{
int m = mat.size(), n = mat[0].size();
vector<vector<int>> sum(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + mat[i - 1][j - 1];
}
}
int ans = INT_MIN;
for (int top = 1; top <= m; top++)
{
for (int bot = top; bot <= m; bot++)
{
set<int> st;
st.insert(0);
for (int r = 1; r <= n; r++)
{
int right = sum[bot][r] - sum[top - 1][r];
auto left = st.lower_bound(right - k);
if (left != st.end())
{
int cur = right - *left;
ans = max(ans, cur);
}
st.insert(right);
}
}
}
return ans;
}
};
``` ```
......
{
"node_id": "dailycode-a6b97887de884133a837b62ae85843c5",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "194d9485ed0a402896a83d0aceb5b0f8",
"author": "csdn.net",
"keywords": "设计,数组,哈希表,数学,随机化"
}
\ No newline at end of file
# O(1) 时间插入、删除和获取随机元素
<p>设计一个支持在<em>平均&nbsp;</em>时间复杂度&nbsp;<strong>O(1)&nbsp;</strong><strong>&nbsp;</strong>执行以下操作的数据结构。</p>
<p><strong>注意: 允许出现重复元素。</strong></p>
<ol>
<li><code>insert(val)</code>:向集合中插入元素 val。</li>
<li><code>remove(val)</code>:当 val 存在时,从集合中移除一个 val。</li>
<li><code>getRandom</code>:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。</li>
</ol>
<p><strong>示例:</strong></p>
<pre>// 初始化一个空的集合。
RandomizedCollection collection = new RandomizedCollection();
// 向集合中插入 1 。返回 true 表示集合不包含 1 。
collection.insert(1);
// 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。
collection.insert(1);
// 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。
collection.insert(2);
// getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。
collection.getRandom();
// 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。
collection.remove(1);
// getRandom 应有相同概率返回 1 和 2 。
collection.getRandom();
</pre>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -71,6 +71,50 @@ ...@@ -71,6 +71,50 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isRectangleCover(vector<vector<int>> &ret)
{
set<pair<int, int>> s;
int x1 = INT_MAX, y1 = INT_MAX, x2 = INT_MIN, y2 = INT_MIN, area = 0;
for (int i = 0; i < ret.size(); ++i)
{
x1 = min(ret[i][0], x1);
x2 = max(ret[i][2], x2);
y1 = min(ret[i][1], y1);
y2 = max(ret[i][3], y2);
area += (ret[i][2] - ret[i][0]) * (ret[i][3] - ret[i][1]);
if (s.find({ret[i][0], ret[i][1]}) == s.end())
s.insert({ret[i][0], ret[i][1]});
else
s.erase({ret[i][0], ret[i][1]});
if (s.find({ret[i][2], ret[i][3]}) == s.end())
s.insert({ret[i][2], ret[i][3]});
else
s.erase({ret[i][2], ret[i][3]});
if (s.find({ret[i][0], ret[i][3]}) == s.end())
s.insert({ret[i][0], ret[i][3]});
else
s.erase({ret[i][0], ret[i][3]});
if (s.find({ret[i][2], ret[i][1]}) == s.end())
s.insert({ret[i][2], ret[i][1]});
else
s.erase({ret[i][2], ret[i][1]});
}
if (s.size() != 4 || !s.count({x1, y1}) || !s.count({x1, y2}) || !s.count({x2, y1}) || !s.count({x2, y2}))
return false;
return area == (x2 - x1) * (y2 - y1);
}
};
``` ```
......
...@@ -34,8 +34,37 @@ ...@@ -34,8 +34,37 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
bool haha(TreeNode *l, TreeNode *r)
{
if (!l && !r)
return true;
if (!l || !r)
return false;
if (l->val != r->val)
return false;
return haha(l->right, r->left) & haha(l->left, r->right);
}
bool isSymmetric(TreeNode *root)
{
if (!root)
return true;
return haha(root->left, root->right);
}
};
``` ```
## 答案 ## 答案
......
...@@ -22,7 +22,34 @@ ...@@ -22,7 +22,34 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int maxDepth(TreeNode *root)
{
int depth = 0;
if (root == NULL)
{
return 0;
}
else
{
depth = max(maxDepth(root->left), maxDepth(root->right));
return 1 + depth;
}
}
};
``` ```
## 答案 ## 答案
......
...@@ -37,8 +37,36 @@ ...@@ -37,8 +37,36 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *sortedArrayToBST(vector<int> &nums)
{
return dfs(nums, 0, nums.size() - 1);
}
TreeNode *dfs(vector<int> &nums, int left, int right)
{
if (left > right)
return NULL;
int mid = (left + right) / 2;
TreeNode *t = new TreeNode(nums[mid]);
t->left = dfs(nums, left, mid - 1);
t->right = dfs(nums, mid + 1, right);
return t;
}
};
``` ```
## 答案 ## 答案
......
...@@ -44,8 +44,39 @@ ...@@ -44,8 +44,39 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int depth(TreeNode *root)
{
if (root == NULL)
return 0;
int left = depth(root->left);
int right = depth(root->right);
return max(left, right) + 1;
}
bool isBalanced(TreeNode *root)
{
if (root == NULL)
return true;
if (abs(depth(root->left) - depth(root->right)) > 1)
return false;
else
return isBalanced(root->left) && isBalanced(root->right);
}
};
``` ```
## 答案 ## 答案
......
...@@ -37,6 +37,29 @@ ...@@ -37,6 +37,29 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int minDepth(TreeNode *root)
{
if (!root)
return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
return (left && right) ? 1 + min(left, right) : 1 + left + right;
}
};
``` ```
## 答案 ## 答案
......
...@@ -42,7 +42,51 @@ ...@@ -42,7 +42,51 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
bool hasPathSum(TreeNode *root, int sum)
{
bool flag = false;
backTrack(root, sum, flag);
return flag;
}
void backTrack(TreeNode *root, int sum, bool &flag)
{
if (!root)
{
return;
}
if (!root->left && !root->right)
{
sum -= root->val;
if (sum == 0)
{
flag = true;
}
sum += root->val;
return;
}
sum -= root->val;
backTrack(root->left, sum, flag);
backTrack(root->right, sum, flag);
sum += root->val;
}
};
``` ```
## 答案 ## 答案
......
...@@ -34,8 +34,48 @@ ...@@ -34,8 +34,48 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<vector<int>> generate(int numRows)
{
if (numRows <= 0)
{
return {};
}
if (numRows == 1)
{
return {{1}};
}
if (numRows == 2)
{
return {{1}, {1, 1}};
}
vector<vector<int>> res = {{1}, {1, 1}};
vector<int> arr;
int row = 1;
while (row < numRows - 1)
{
arr.push_back(1);
for (int i = 0; i < res[row].size() - 1; i++)
{
int temp = 0;
temp = res[row][i] + res[row][i + 1];
arr.push_back(temp);
}
arr.push_back(1);
res.push_back(arr);
arr.clear();
row++;
}
return res;
}
};
``` ```
## 答案 ## 答案
......
...@@ -47,8 +47,25 @@ ...@@ -47,8 +47,25 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> getRow(int rowIndex)
{
vector<int> res(rowIndex + 1, 1);
for (int i = 0; i < rowIndex + 1; ++i)
{
for (int j = i - 1; j > 0; --j)
{
res[j] = res[j] + res[j - 1];
}
}
return res;
}
};
``` ```
## 答案 ## 答案
......
...@@ -39,7 +39,31 @@ ...@@ -39,7 +39,31 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
int profit = INT_MIN;
int buy = INT_MAX;
for (int i = 0; i < prices.size(); i++)
{
int temp = prices[i] - buy;
if (temp > profit)
{
profit = temp;
}
if (temp < 0)
{
buy = prices[i];
}
}
return (profit > 0) ? profit : 0;
}
};
``` ```
## 答案 ## 答案
......
...@@ -46,7 +46,25 @@ ...@@ -46,7 +46,25 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
if (prices.empty())
return 0;
int cnt = 0;
for (int i = 0; i < prices.size() - 1; ++i)
{
if (prices[i] < prices[i + 1])
cnt += prices[i + 1] - prices[i];
}
return cnt;
}
};
``` ```
......
...@@ -36,7 +36,42 @@ ...@@ -36,7 +36,42 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isPalindrome(string s)
{
int left = 0, right;
if ((right = s.size()) == 0)
{
return true;
}
while (left < right)
{
while (left < right && !isalnum(s[left]))
{
left++;
}
while (left < right && !isalnum(s[right]))
{
right--;
}
if (left < right)
{
if (tolower(s[left]) != tolower(s[right]))
{
return false;
}
}
left++;
right--;
}
return true;
}
};
``` ```
## 答案 ## 答案
......
...@@ -22,7 +22,22 @@ ...@@ -22,7 +22,22 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int singleNumber(vector<int> &nums)
{
int res = 0;
for (int i = 0; i < nums.size(); i++)
{
res ^= nums[i];
}
return res;
}
};
``` ```
## 答案 ## 答案
......
...@@ -55,8 +55,38 @@ ...@@ -55,8 +55,38 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
bool hasCycle(ListNode *head)
{
ListNode *faster = head;
ListNode *slower = head;
if (head == NULL)
return false;
while (faster != NULL && faster->next != NULL)
{
faster = faster->next->next;
slower = slower->next;
if (faster == slower)
return true;
}
return false;
}
};
``` ```
## 答案 ## 答案
......
...@@ -57,7 +57,30 @@ ...@@ -57,7 +57,30 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
private:
void rec(TreeNode *root, vector<int> &ret)
{
if (root != NULL)
{
rec(root->right, ret);
rec(root->left, ret);
ret.push_back(root->val);
}
}
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> ret;
rec(root, ret);
return ret;
}
};
``` ```
## 答案 ## 答案
......
...@@ -20,7 +20,27 @@ ...@@ -20,7 +20,27 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> postorderTraversal(TreeNode *root)
{
dfs(root);
return temp;
}
void dfs(TreeNode *root)
{
if (root == NULL)
return;
dfs(root->left);
dfs(root->right);
temp.push_back(root->val);
}
vector<int> temp;
};
``` ```
## 答案 ## 答案
......
...@@ -43,7 +43,44 @@ minStack.getMin(); --&gt; 返回 -2. ...@@ -43,7 +43,44 @@ minStack.getMin(); --&gt; 返回 -2.
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class MinStack
{
public:
stack<int> s;
stack<int> min;
/** initialize your data structure here. */
MinStack()
{
}
void push(int x)
{
s.push(x);
if (min.empty() || x <= min.top())
{
min.push(x);
}
}
void pop()
{
if (s.top() == min.top())
min.pop();
s.pop();
}
int top()
{
return s.top();
}
int getMin()
{
return min.top();
}
};
``` ```
......
{
"node_id": "dailycode-4de24aa0c7344f25857309f39049cdd6",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "4e5af08303f447cbb36a145d372a4c3e",
"author": "csdn.net",
"keywords": "字符串,交互,模拟"
}
\ No newline at end of file
# 用 Read4 读取 N 个字符
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -72,6 +72,30 @@ ...@@ -72,6 +72,30 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
if (!headA || !headB)
{
return NULL;
}
ListNode *cur1 = headA;
ListNode *cur2 = headB;
while (cur1 != cur2)
{
cur1 = cur1 ? cur1->next : headB;
cur2 = cur2 ? cur2->next : headA;
}
return cur1;
}
};
``` ```
......
{
"node_id": "dailycode-5ade162d0e4f4101a1b2c496cc8dda01",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "ff805edfb4704a099d16f5b37079956e",
"author": "csdn.net",
"keywords": "数组"
}
\ No newline at end of file
# 缺失的区间
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -46,7 +46,34 @@ ...@@ -46,7 +46,34 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
int low = 0, high = numbers.size() - 1;
while (low < high)
{
int sum = numbers[low] + numbers[high];
if (sum == target)
{
return {low + 1, high + 1};
}
if (sum < target)
{
++low;
}
else
{
--high;
}
}
return {-1, -1};
}
}
``` ```
## 答案 ## 答案
......
...@@ -57,7 +57,31 @@ AB -> 28 ...@@ -57,7 +57,31 @@ AB -> 28
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
string convertToTitle(int n)
{
string res;
while (n)
{
int temp = n % 26;
n /= 26;
if (temp)
res.push_back('A' + temp - 1);
else
{
res.push_back('Z');
n--;
}
}
reverse(res.begin(), res.end());
return res;
}
};
``` ```
......
...@@ -32,7 +32,28 @@ ...@@ -32,7 +32,28 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int majorityElement(vector<int> &nums)
{
unordered_map<int, int> counts;
int majority = 0, cnt = 0;
for (int num : nums)
{
++counts[num];
if (counts[num] > cnt)
{
majority = num;
cnt = counts[num];
}
}
return majority;
}
};
``` ```
## 答案 ## 答案
......
{
"node_id": "dailycode-9a10dbfc78084378b9158b62dd73cbf6",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "b2bddd35d61c408d9282619451a3f324",
"author": "csdn.net",
"keywords": "设计,数组,哈希表,双指针,数据流"
}
\ No newline at end of file
# 两数之和 III
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -60,7 +60,24 @@ ...@@ -60,7 +60,24 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int titleToNumber(string s)
{
long num = 0;
for (int i = 0; i < s.size(); i++)
{
num = (num * 26) + (s[i] - 64);
}
return num;
}
};
``` ```
......
...@@ -45,6 +45,35 @@ ...@@ -45,6 +45,35 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int trailingZeroes(int n)
{
int numOfZeros = 0;
while (n > 0)
{
numOfZeros += numOf5(n);
n--;
}
return numOfZeros;
}
int numOf5(int num)
{
int count = 0;
while ((num > 1) && (num % 5 == 0))
{
count++;
num /= 5;
}
return count;
}
};
``` ```
......
{
"node_id": "dailycode-85f7b312e21846f69643bb88236a2bdf",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "dd9e054c96174629b626b0321a29c566",
"author": "csdn.net",
"keywords": "数据库"
}
\ No newline at end of file
# 组合两个表
<p>表1: <code>Person</code></p>
<pre>+-------------+---------+
| 列名 | 类型 |
+-------------+---------+
| PersonId | int |
| FirstName | varchar |
| LastName | varchar |
+-------------+---------+
PersonId 是上表主键
</pre>
<p>表2: <code>Address</code></p>
<pre>+-------------+---------+
| 列名 | 类型 |
+-------------+---------+
| AddressId | int |
| PersonId | int |
| City | varchar |
| State | varchar |
+-------------+---------+
AddressId 是上表主键
</pre>
<p>&nbsp;</p>
<p>编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供&nbsp;person 的以下信息:</p>
<p>&nbsp;</p>
<pre>FirstName, LastName, City, State
</pre>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-f292aee831624f71bbffe40a7326e60c",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "5b3f07f1ef3e468aae341b4bd2a98e6e",
"author": "csdn.net",
"keywords": "数据库"
}
\ No newline at end of file
# 第二高的薪水
<p>编写一个 SQL 查询,获取 <code>Employee</code>&nbsp;表中第二高的薪水(Salary)&nbsp;</p>
<pre>+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
</pre>
<p>例如上述&nbsp;<code>Employee</code>&nbsp;表,SQL查询应该返回&nbsp;<code>200</code> 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 <code>null</code></p>
<pre>+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
</pre>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-8cb377183b7f43e494561b64ebb63857",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "d6c4a46b82b843559ac48dae21bcfe29",
"author": "csdn.net",
"keywords": "数据库"
}
\ No newline at end of file
# 超过经理收入的员工
<p><code>Employee</code>&nbsp;表包含所有员工,他们的经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id。</p>
<pre>+----+-------+--------+-----------+
| Id | Name | Salary | ManagerId |
+----+-------+--------+-----------+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
+----+-------+--------+-----------+
</pre>
<p>给定&nbsp;<code>Employee</code>&nbsp;表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。</p>
<pre>+----------+
| Employee |
+----------+
| Joe |
+----------+
</pre>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-54c93f55f2ff4886b15ec70c9f7a7520",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "9978a8ccf34d47a9b9e08644fbca7f80",
"author": "csdn.net",
"keywords": "数据库"
}
\ No newline at end of file
# 查找重复的电子邮箱
<p>编写一个 SQL 查询,查找&nbsp;<code>Person</code> 表中所有重复的电子邮箱。</p>
<p><strong>示例:</strong></p>
<pre>+----+---------+
| Id | Email |
+----+---------+
| 1 | a@b.com |
| 2 | c@d.com |
| 3 | a@b.com |
+----+---------+
</pre>
<p>根据以上输入,你的查询应返回以下结果:</p>
<pre>+---------+
| Email |
+---------+
| a@b.com |
+---------+
</pre>
<p><strong>说明:</strong>所有电子邮箱都是小写字母。</p>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-bf76bddb51ea4b049b9eaa7441aa6588",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "0a7c83632c9544f9aa006e8bd4519510",
"author": "csdn.net",
"keywords": "数据库"
}
\ No newline at end of file
# 从不订购的客户
<p>某网站包含两个表,<code>Customers</code> 表和 <code>Orders</code> 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。</p>
<p><code>Customers</code> 表:</p>
<pre>+----+-------+
| Id | Name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+
</pre>
<p><code>Orders</code> 表:</p>
<pre>+----+------------+
| Id | CustomerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+
</pre>
<p>例如给定上述表格,你的查询应返回:</p>
<pre>+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+
</pre>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -43,7 +43,26 @@ ...@@ -43,7 +43,26 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
uint32_t reverseBits(uint32_t n)
{
uint32_t res = 0;
for (int i = 0; i < 32; i++)
{
res <<= 1;
res |= n & 1;
n >>= 1;
}
return res;
}
};
``` ```
......
...@@ -59,7 +59,27 @@ ...@@ -59,7 +59,27 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int hammingWeight(uint32_t n)
{
int count = 0;
uint32_t res = 1;
for (int i = 0; i < 32; i++)
{
if (res & n)
{
count++;
}
n >>= 1;
}
return count;
}
};
``` ```
......
{
"node_id": "dailycode-1352eaf10ae34a0ca9aa92949beb3c8d",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "ca6c196606004fa4ab6e8463b4d867fb",
"author": "csdn.net",
"keywords": "shell"
}
\ No newline at end of file
# 有效电话号码
<p>给定一个包含电话号码列表(一行一个电话号码)的文本文件 <code>file.txt</code>,写一个单行 bash 脚本输出所有有效的电话号码。</p>
<p>你可以假设一个有效的电话号码必须满足以下两种格式: (xxx) xxx-xxxx 或 xxx-xxx-xxxx。(x 表示一个数字)</p>
<p>你也可以假设每行前后没有多余的空格字符。</p>
<p> </p>
<p><strong>示例:</strong></p>
<p>假设 <code>file.txt</code> 内容如下:</p>
<pre>
987-123-4567
123 456 7890
(123) 456-7890
</pre>
<p>你的脚本应当输出下列有效的电话号码:</p>
<pre>
987-123-4567
(123) 456-7890
</pre>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-c78b9d1362f846a3a49e8af24ce85cc3",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "522b8d3fc3c04c9d9926dc1b65a18403",
"author": "csdn.net",
"keywords": "shell"
}
\ No newline at end of file
# 第十行
<p>给定一个文本文件&nbsp;<code>file.txt</code>,请只打印这个文件中的第十行。</p>
<p><strong>示例:</strong></p>
<p>假设&nbsp;<code>file.txt</code> 有如下内容:</p>
<pre>Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
</pre>
<p>你的脚本应当显示第十行:</p>
<pre>Line 10
</pre>
<p><strong>说明:</strong><br>
1. 如果文件少于十行,你应当输出什么?<br>
2. 至少有三种不同的解法,请尝试尽可能多的方法来解题。</p>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-807994a6110843e28221362d4a038abd",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "c2759b89ec514f61b350829d2197e361",
"author": "csdn.net",
"keywords": "数据库"
}
\ No newline at end of file
# 删除重复的电子邮箱
<p>编写一个 SQL 查询,来删除&nbsp;<code>Person</code>&nbsp;表中所有重复的电子邮箱,重复的邮箱里只保留&nbsp;<strong>Id&nbsp;</strong><em>最小&nbsp;</em>的那个。</p>
<pre>+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
| 3 | john@example.com |
+----+------------------+
Id 是这个表的主键。
</pre>
<p>例如,在运行你的查询语句之后,上面的 <code>Person</code> 表应返回以下几行:</p>
<pre>+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
+----+------------------+
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li>执行 SQL 之后,输出是整个 <code>Person</code>&nbsp;表。</li>
<li>使用 <code>delete</code> 语句。</li>
</ul>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
{
"node_id": "dailycode-6ca678258ebb4b49b1ed247761ee7594",
"keywords": [],
"children": [],
"keywords_must": [],
"keywords_forbid": [],
"export": [
"solution.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"source": "solution.md",
"exercise_id": "d01e6eb74ba84d4d9273ceaafd110640",
"author": "csdn.net",
"keywords": "数据库"
}
\ No newline at end of file
# 上升的温度
<div class="original__bRMd">
<div>
<p><code>Weather</code></p>
<pre>
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| recordDate | date |
| temperature | int |
+---------------+---------+
id 是这个表的主键
该表包含特定日期的温度信息</pre>
<p> </p>
<p>编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 <code>id</code></p>
<p>返回结果 <strong>不要求顺序</strong></p>
<p>查询结果格式如下例:</p>
<pre>
<code>Weather</code>
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+----+------------+-------------+
Result table:
+----+
| id |
+----+
| 2 |
| 4 |
+----+
2015-01-02 的温度比前一天高(10 -> 25)
2015-01-04 的温度比前一天高(20 -> 30)
</pre>
</div>
</div>
## template
```cpp
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```
\ No newline at end of file
...@@ -46,7 +46,33 @@ ...@@ -46,7 +46,33 @@
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isHappy(int n)
{
set<int> s;
while (n != 1)
{
int t = 0;
while (n)
{
t += (n % 10) * (n % 10);
n /= 10;
}
int size = s.size();
s.insert(t);
if (size == s.size())
return false;
n = t;
}
return true;
}
};
``` ```
## 答案 ## 答案
......
...@@ -38,7 +38,42 @@ ...@@ -38,7 +38,42 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *removeElements(ListNode *head, int val)
{
ListNode *dumynode = new ListNode(0);
dumynode->next = head;
ListNode *fast = dumynode->next;
ListNode *slow = dumynode;
while (fast != NULL)
{
if (fast->val == val)
{
slow->next = slow->next->next;
}
else
{
slow = slow->next;
}
fast = fast->next;
}
ListNode *ret = dumynode->next;
delete dumynode;
return ret;
}
};
``` ```
......
...@@ -35,7 +35,30 @@ ...@@ -35,7 +35,30 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int countPrimes(int n)
{
vector<bool> primesMap(n, true);
int count = 0;
for (int i = 2; i < n; i++)
{
if (primesMap[i])
{
count++;
for (int j = 2 * i; j < n; j += i)
{
primesMap[j] = false;
}
}
}
return count;
}
};
``` ```
......
...@@ -39,7 +39,35 @@ ...@@ -39,7 +39,35 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isIsomorphic(string s, string t)
{
vector<int> m(128, -1);
for (int i = 0; i < s.size(); ++i)
{
if (m[s[i]] != -1)
{
if (m[s[i]] != t[i])
return false;
}
else
{
for (auto v : m)
{
if (v == t[i])
return false;
}
m[s[i]] = t[i];
}
}
return true;
}
};
``` ```
......
...@@ -45,6 +45,42 @@ ...@@ -45,6 +45,42 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *reverseList(ListNode *head)
{
if (head == NULL)
return NULL;
ListNode *node = NULL;
ListNode *temp = head;
ListNode *temp1 = head;
while (true)
{
if (temp->next == NULL)
{
temp1 = temp;
temp1->next = node;
break;
}
temp1 = temp;
temp = temp->next;
temp1->next = node;
node = temp1;
}
return temp1;
}
};
``` ```
......
...@@ -28,7 +28,29 @@ ...@@ -28,7 +28,29 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool containsDuplicate(vector<int> &nums)
{
if (nums.empty())
{
return false;
}
sort(nums.begin(), nums.begin() + nums.size());
for (int i = 0; i < nums.size() - 1; i++)
{
if (nums[i] == nums[i + 1])
{
return true;
}
}
return false;
}
};
``` ```
......
...@@ -23,7 +23,32 @@ ...@@ -23,7 +23,32 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool containsNearbyDuplicate(vector<int> &nums, int k)
{
int n = nums.size(), idx = 0;
unordered_map<int, int> nmap;
for (int i = 0; i < n; ++i)
{
auto iter = nmap.find(nums[i]);
if (iter != nmap.end())
{
if (i - iter->second <= k)
return true;
else
iter->second = i;
}
else
nmap[nums[i]] = i;
}
return false;
}
};
``` ```
......
...@@ -58,7 +58,48 @@ myStack.empty(); // 返回 False ...@@ -58,7 +58,48 @@ myStack.empty(); // 返回 False
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class MyStack
{
public:
MyStack()
{
}
void push(int x)
{
std::queue<int> temp_queue;
temp_queue.push(x);
while (!_data.empty())
{
temp_queue.push(_data.front());
_data.pop();
}
while (!temp_queue.empty())
{
_data.push(temp_queue.front());
temp_queue.pop();
}
}
int pop()
{
int x = _data.front();
_data.pop();
return x;
}
int top()
{
return _data.front();
}
bool empty()
{
return _data.empty();
}
private:
std::queue<int> _data;
};
``` ```
......
...@@ -29,7 +29,32 @@ ...@@ -29,7 +29,32 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *invertTree(TreeNode *root)
{
if (!root)
{
return root;
}
TreeNode *temp = root->left;
root->left = invertTree(root->right);
root->right = invertTree(temp);
return root;
}
};
``` ```
......
...@@ -72,7 +72,31 @@ ...@@ -72,7 +72,31 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<string> summaryRanges(vector<int> &nums)
{
int n = nums.size();
vector<string> ans;
int i = 0;
while (i < n)
{
int j = i;
while (j + 1 < n && nums[j + 1] == nums[j] + 1)
j++;
if (i == j)
ans.push_back(to_string(nums[i]));
else
ans.push_back(to_string(nums[i]) + "->" + to_string(nums[j]));
i = j + 1;
}
return ans;
}
};
``` ```
......
...@@ -59,7 +59,22 @@ ...@@ -59,7 +59,22 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isPowerOfTwo(int n)
{
int cur = 0;
for (int i = 0; i < 31; i++)
{
cur += (n >> i) & 1;
}
return n > 0 && cur == 1;
}
};
``` ```
......
...@@ -65,7 +65,55 @@ myQueue.empty(); // return false ...@@ -65,7 +65,55 @@ myQueue.empty(); // return false
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
class MyQueue
{
public:
/** Initialize your data structure here. */
stack<int> a, b;
MyQueue()
{
}
/** Push element x to the back of queue. */
void push(int x)
{
while (!b.empty())
{
a.push(b.top());
b.pop();
}
b.push(x);
while (!a.empty())
{
b.push(a.top());
a.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop()
{
int res = b.top();
b.pop();
return res;
}
/** Get the front element. */
int peek()
{
return b.top();
}
/** Returns whether the queue is empty. */
bool empty()
{
return b.empty();
}
};
``` ```
......
...@@ -35,7 +35,35 @@ ...@@ -35,7 +35,35 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
bool isPalindrome(ListNode *head)
{
vector<int> v;
while (head != NULL)
{
v.push_back(head->val);
head = head->next;
}
for (int i = 0; i < v.size(); i++)
{
if (v[i] != v[v.size() - i - 1])
return false;
}
return true;
}
};
``` ```
......
...@@ -36,6 +36,31 @@ ...@@ -36,6 +36,31 @@
## template ## template
```cpp ```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
if (root == NULL)
return NULL;
if ((root->val > q->val) && (root->val > p->val))
return lowestCommonAncestor(root->left, p, q);
else if ((root->val < q->val) && (root->val < p->val))
return lowestCommonAncestor(root->right, p, q);
return root;
}
};
``` ```
......
...@@ -35,6 +35,37 @@ ...@@ -35,6 +35,37 @@
```java ```java
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isSymmetric(root.left, root.right);
}
public boolean isSymmetric(TreeNode n1, TreeNode n2) {
if (n1 == null || n2 == null) {
return n1 == n2;
}
if (n1.val != n2.val) {
return false;
}
return isSymmetric(n1.left, n2.right) && isSymmetric(n1.right, n2.left);
}
}
``` ```
......
...@@ -221,6 +221,7 @@ def update_it_konwledge(): ...@@ -221,6 +221,7 @@ def update_it_konwledge():
answer = answer.strip() answer = answer.strip()
print(file) print(file)
assert answer in choice_list_res assert answer in choice_list_res
assert len(choice_list_res) >= 4
question_id = file_name question_id = file_name
choice_list_remove = [] choice_list_remove = []
for idx, val in enumerate(choice_list_res): for idx, val in enumerate(choice_list_res):
......
...@@ -411,7 +411,7 @@ class TreeWalker: ...@@ -411,7 +411,7 @@ class TreeWalker:
def default_notebook(self): def default_notebook(self):
if self.enable_notebook is not None: if self.enable_notebook is not None:
return self.enable_notebook return self.enable_notebook
if self.name in ["python", "java", "c"]: if self.name in ["python", "java", "c", "dailycode"]:
return True return True
else: else:
return False return False
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册