LeetCode每日一题,原题链接
LeetCode-1574. 删除最短的子数组使剩余数组有序
题目描述:
给你一个整数数组 arr ,请你删除一个子数组(可以为空),使得 arr 中剩下的元素是 非递减 的。
一个子数组指的是原数组中连续的一个子序列。
请你返回满足题目要求的最短子数组的长度。
解题思路:最关键的一点是意识到,一共只可以删除掉一个连续的子数组,用动态规划是不可以的,因此需要考虑子数组出现的地方,一共有三个地方可以出现待删除子数组,分别是:
前缀、后缀、中间
既然这样,就可以分三种情况去讨论,如果要删除的是前缀,那只需找到最长的非递减后缀,删除后缀同理要找到最长非递减前缀。如果要删除中间,要意识到上一步求到的前后缀可以重复使用,也就是删除中间后,剩下的一定是前缀的前面部分和后缀的后面部分的组合。代码如下:
class Solution {
public:
int findLengthOfShortestSubarray(vector<int>& arr) {
int aSize = arr.size();
if(aSize == 0) return 0;
int result;
int l = 0;
int r = aSize - 1;
while (l + 1 < aSize && arr[l] <= arr[l + 1]) {
++l;
}
while (r - 1 >= 0 && arr[r - 1] <= arr[r]) {
--r;
}
if(l >= r) return 0;
result = min(aSize- l - 1, r);
for(int i = 0; i <= l; i++){
for(int j = r; j < aSize; j++){
if(arr[j] >= arr[i]){
result = min(result, j - i -1);
break;
}
}
}
return result;
}
};
顺序刷题,二叉树板块
257. 二叉树的所有路径
正常前序遍历递归做,注意打印格式即可,打印的逻辑隐含了回溯的思想
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
if(!root) return result;
string path = "";
getPath(root, path, result);
return result;
}
void getPath(TreeNode* &root, string path, vector<string> &result){
path += to_string(root->val);
if(!root->left && !root->right){
result.push_back(path);
return;
}
if(root->left){
getPath(root->left, path + "->", result);
}
if(root->right){
getPath(root->right, path + "->", result);
}
}
};
LeetCode-404. 左叶子之和
前序递归处理,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root) return 0;
int sum = 0;
getSum(root, false, sum);
return sum;
}
void getSum(TreeNode* root, bool isLeft, int& sum){
if(isLeft && !root->left && !root->right){
sum += root->val;
return;
}
if(root->left){
getSum(root->left, true, sum);
}
if(root->right){
getSum(root->right, false, sum);
}
return;
}
};