码迷,mamicode.com
首页 > 移动开发 > 详细

Trapping Rain Water

时间:2014-10-29 12:12:50      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   使用   for   sp   

使用栈结构解决。

#include <iostream>
#include <stack>
using namespace std;

class Solution {
public:
    int trap(int A[], int n) {
if (n<3){ return 0; }
stack
<int> water_stack; int begin=0; int res=0;
for (int i =0;i<n;++i){ if (A[i]>0 && water_stack.empty()){ water_stack.push(A[i]); begin=A[i]; continue; } if (A[i]<begin){ water_stack.push(A[i]); continue; } if (A[i]>=begin && begin!=0){ while(!water_stack.empty()){ //cout<<"A"<<i<<": "<<A[i]; //cout<<" begin: "<<begin; //cout<<" top: "<<water_stack.top()<<endl; res+=begin-water_stack.top(); water_stack.pop(); } water_stack.push(A[i]); begin=A[i]; } //cout<<"res: "<<res<<endl; }
int end=0; while(!water_stack.empty()){ if(water_stack.top()>=end){ end=water_stack.top(); water_stack.pop(); } else{ res+=end-water_stack.top(); water_stack.pop(); } }
return res; } }; int main(int argc, char** argv) { Solution s; int A[]={0,1,0,2,1,0,1,3,2,1,2,1}; cout<<s.trap(A,12); return 0; }

 写的并不完美,看起来是为了用栈而用栈,其实不用栈也能解决。

Trapping Rain Water

标签:style   blog   io   color   os   ar   使用   for   sp   

原文地址:http://www.cnblogs.com/iois/p/4058901.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!