leetcode 665
2024-09-06 08:06:01
665. Non-decreasing Array
Input: [4,2,3]
Output: True
Explanation: You could modify the first4
to1
to get a non-decreasing array.递增
思路:贪心思想,找异常值,存在两个以上则返回false。如果当前的值比前一的值小,并且也比前两的值小,此时只需更改当前值,而不更改前两个值。
更改规则是用前一的值代替当前值。
两种情况
例如: 2 2 1 -》 2 2 2
0 2 1 -》 0 1 1
bool checkPossibility(vector<int>& nums) {
int cnt = ; //如果存在两个以上的异常值则直接返回false
for(int i = ; i < nums.size() && cnt<= ; i++){
if(nums[i-] > nums[i]){ //存在异常值
cnt++;
if(i-< || nums[i-] <= nums[i])nums[i-] = nums[i]; //i-2处理第一个边界值,这种||技巧经常用到
else nums[i] = nums[i-]; //have to modify nums[i]
}
}
return cnt<=;
}
669. Trim a Binary Search Tree
Input:
3
/ \
0 4
\
2
/
1 L = 1
R = 3 Output:
3
/
2
/
1
The code works as recursion. If the root value in the range [L, R]
we need return the root, but trim its left and right subtree;
else if the root value < L
because of binary search tree property, the root and the left subtree are not in range;
we need return trimmed right subtree.
else
similarly we need return trimmed left subtree. Without freeing memory class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if (root == NULL) return NULL;
if (root->val < L) return trimBST(root->right, L, R);
if (root->val > R) return trimBST(root->left, L, R);
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}
};
总结:树的遍历bfs,一般结构:
当前root
////////////////////////////
中间逻辑,比如深一层的遍历
///////////////////////////
对当前root进行操作,例如左右边子树的赋值操作
最新文章
- JSON: Property &#39;xxx&#39; has no getter method的解决办法
- 转--Invalidate和postInvalidate的更新view区别
- CSS and JavaScript Bundling and Minification in ASP.NET 4.5
- bind()
- 小议window.event || ev
- Swift中出现“no such module cocoa”的错误
- ASP.NET获取IP的6种方法(转载于LanceZhang&#39;s Tech Blog)
- C# CreateParams的使用(解决闪屏问题)
- Linux下GitLab服务器搭建
- java 诊断工具——Arthas
- 使用FileZilla从Linux系统下载文件
- 使用git将项目上传到github
- C++中多维数组传递参数
- 新装的arcgis10.5特别卡
- 如何将指定文件或文件夹直接提交到svn指定目录
- USB2.0学习笔记连载(十四):USB驱动安装及固件程序的编写
- 库、教程、论文实现,这是一份超全的PyTorch资源列表(Github 2.2K星)
- mybatis匹配字符串的坑
- PL/SQL Developer 和 Instant Client客户端安装配置
- OO学习体会与阶段总结(设计与实现)
热门文章
- idea设置编码格式utf-8
- JS流程控制语句 来来回回(Do...while循环) 先执行后判断 do while结构的基本原理和while结构是基本相同的,但是它保证循环体至少被执行一次。
- 宽域POST提交数据
- layui相关用法总结
- slam课程
- 新书《iOS应用逆向工程:分析与实战》
- 线段树分治初步学习&;洛谷P5227[AHOI2013]连通图
- [原创]Java调用PageOffice给Word中的Table赋值
- 2019-10-31-C#-dotnet-获取整个局域网的-ip-地址
- Nginx简介与基础配置