Minimum Depth of Binary Tree & Length of Last Word & Trapping Rain Water
来源:互联网 发布:app基础表数据库设计 编辑:程序博客网 时间:2024/05/10 16:30
(1) Minimum Depth of Binary Tree
class Solution {private: void solve(TreeNode *root, int curDep, int &minDep){ if(!root) return; if(!root->left && !root->right) { minDep=min(curDep,minDep); return; } curDep++; solve(root->left,curDep,minDep); solve(root->right,curDep,minDep); }public: int minDepth(TreeNode *root) { if(!root) return 0; int minDep=1000000; solve(root,1,minDep); return minDep; }};另一种不需要预设最小值得方法[1]。
(2) Length of Last Word
class Solution {public: int lengthOfLastWord(const char *s) { char cur=*s; int i=0,len=0,prelen=0; while(cur!='\0') if(cur==' ') { prelen=len>0?len:prelen; len=0; i++; cur=*(s+i); if(cur=='\0') return prelen; } else { len++; i++; cur=*(s+i); } return len; }};
(3) Trapping Rain Water
根据[2]: 对某个值A[i]来说,能trapped的最多的water取决于在i之前最高的值leftMostHeight[i]和在i右边的最高的值rightMostHeight[i](均不包含自身)。
如果min(left,right) > A[i],那么在i这个位置上能trapped的water就是min(left,right) – A[i]。
有了这个想法就好办了,第一遍从左到右计算数组leftMostHeight,第二遍从右到左计算rightMostHeight。
时间复杂度是O(n)。
class Solution {public: int trap(int A[], int n) { int curHeight=A[0],sum=0; int leftHighest[n],rightHightest[n],maxHeight,water,high; maxHeight=0; for(int i=0;i<n;i++) { leftHighest[i]=maxHeight; maxHeight=max(maxHeight,A[i]); } maxHeight=0; for(int i=n-1;i>=0;i--) { rightHightest[i]=maxHeight; maxHeight=max(maxHeight,A[i]); } water=0; for(int i=0;i<n;i++) { high=min(leftHighest[i],rightHightest[i])-A[i]; if(high>0) water+=high; } return water; }};
参考:
[1]http://www.cnblogs.com/remlostime/archive/2012/11/12/2766608.html
[2]http://blog.csdn.net/doc_sgl/article/details/12307171
0 0
- Minimum Depth of Binary Tree & Length of Last Word & Trapping Rain Water
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- showModalDialog传参,刷新父窗体,关闭
- maven 入门教程
- Application,Session,Cookie,ViewState和Cache生命周期
- STL之vector的使用
- iosLearningDiary_Xcode不太常见又实用的小技巧
- Minimum Depth of Binary Tree & Length of Last Word & Trapping Rain Water
- 那年第几天是什么日期
- 我们纵情声色不过以此为寄 我们坚强不过是彼此相欺 最云淡风的字眼 却包含我最深厚的问候和想念
- 阿里巴巴、腾讯、百度面试笔试题知识点汇总(二)
- C++关于动态申请空间的一个问题
- jbpm 4.4 eclipse 插件安装失败
- 使用VS开发Windows服务程序
- UCGUI窗体管理及消息处理机制分析
- PS 滤镜算法原理——高反差保留 (High Pass)