leetcode_c++:trappint rain water(042)
2016-05-23 01:21
393 查看
题目
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Subscribe to see which companies asked this question
算法
O(N)为3*12的矩阵,两个1之间为水量;
#include<iostream> #include<vector> #include <algorithm> using namespace std; /*扫描3*12的矩阵的每一行,两个1之间为水量*/ class Solution { public: int trap(vector<int>& height) { int maxi=0,peak=0,sum=0; int n=height.size(); // get the max position for(int i=0;i<n;i++) if(height[maxi]<height[i]) maxi=i; //first part:forward to maxi for(int i=0;i<maxi;++i){ if(height[i]<peak) peak=height[i]; else sum+=peak-height[i]; } //second: 往后找 peak=0; for(int i=n-1;i>maxi;--i){ if(height[i]>peak) peak=height[i]; else sum+=peak-height[i]; } return sum; } };
相关文章推荐
- 以太坊(Ethereum)开发框架 Truffle:引言
- webView简单使用:网页中有电话,在客户端点击打电话(一)
- [读书笔记]Android IPC机制(一)
- Android基础之SQLite的使用
- android LRUCache解析
- Android笔记(十六)文件存储
- 兄台息怒,关于arguments,您的想法和大神是一样一样的----闲聊JS中的apply和call
- android 简单的网格布局 GridLayout
- 当你关闭朋友圈后,微信对你做了什么?
- kappa一致性检验
- 微信月活跃用户破7.6亿,即将赶上QQ
- flask添加权限的时候出现TypeError: ObjectId('') is not JSON
- 微信公众号——信息理解
- iOS简易版的 仿popviewcontroller 功能
- iOStableView 自动布局常见问题之页面滑动到最底时,下面多出44的距离!
- 怎样免费注册apple id
- Android 听筒 扬声器 切换
- Android每个activity背景铺满整个屏幕包括标题栏
- Android 倒计时
- 在appstore里面搜索android会出现哪些鬼?