有意思的数学题:Trapping Rain Water
2016-02-08 17:10
375 查看
LeetCode传送门 https://leetcode.com/problems/trapping-rain-water/
Trapping Rain Water
ps:有没有对我感兴趣的boss收留~附交友地址一枚https://github.com/zrss
简单粗暴的resume:https://github.com/zrss/ghostblog,近期再修改下
#include <iostream> #include <vector> using namespace std; class Solution { public: int trap(vector<int>& height) { if (height.size() == 0) { return 0; } int water = 0; int preIndex = 0; int preHeight = 0; // 找到第一个高度非0的bar while (preIndex < height.size() - 1 && height[preIndex] == 0) { ++preIndex; } if (preIndex == height.size() - 1) { return 0; } // 遍历 while (preIndex < height.size()) { preHeight = height[preIndex]; // 寻找更高的或相等的bar // 同时记录遍历过的最高的bar // 如果寻找不到更高的或相等的bar时,使用记录值计算 int next = preIndex + 1; int minHeight = 0; int minIndex = next; while (next < height.size() && height[next] < preHeight) { if (height[next] > minHeight) { minHeight = height[next]; minIndex = next; } ++next; } // 如果找到 if (next != height.size()) { water += (preHeight * (next - preIndex - 1)); // 计算总面积 for (int i = preIndex + 1; i < next; ++i) { // 减去中间bar面积 water -= height[i]; } preIndex = next; // 从找到的bar开始下一次的迭代 } else { water += (minHeight * (minIndex - preIndex - 1)); // 计算总面积 for (int i = preIndex + 1; i < minIndex; ++i) { // 减去中间bar面积 water -= height[i]; } preIndex = minIndex; // 从次高的bar开始 } } return water; } }; int main(int argc, char const *argv[]) { Solution solution; vector<int> height = {0,1,0,2,1,0,1,3,2,1,2,1}; cout << solution.trap(height) << endl; return 0; }
Trapping Rain Water
闲聊一二
大年初一!祝大家猴年快乐啦,已经工作的童鞋升职加薪,要实习、找工作的童鞋offer多多~博主今年也要面对找实习、找工作的人生大事儿了。好久没写博客了,默默的哀悼上个学期,自己瞎折腾,弄出的不成熟的东西。希望猴年是激情,奋斗,收获的一年~ps:有没有对我感兴趣的boss收留~附交友地址一枚https://github.com/zrss
简单粗暴的resume:https://github.com/zrss/ghostblog,近期再修改下
相关文章推荐
- iOS 基础题
- Swift快速入门(三)运算符
- Android算命小程序的实现
- Android报错:Your content must have a ListView whose id attribute is 'android.R.id.list'
- Android图像单位转换
- 炉石传说斩杀计算器-Android
- JavaScript操作canvas制作前端H5小游戏——Flappy Bird
- Android RemoteViews 11问11答
- ANDROID_MARS学习笔记_S01_005CheckBox
- ANDROID_MARS学习笔记_S01_004dpi、dp(dip)及计算
- Intent(意图)转跳页面
- cocos2d-x 帧动画创建一
- Unity3D NGUI,uGUI总结
- 需求 - 17 - “录制圈”
- cocos2dx3.2 异步加载和动态加载
- cocos2dx3.0 超级马里奥开发笔记(一)——loadingbar、TableView和pageview的使用
- IoSkipCurrentIrpStackLocation macro
- IoSetCompletionRoutine routine
- 解决cocoapods在64位iOS7系统以下的警告问题
- 安卓-APP安装后多个图标的解决