leetcode 42. Trapping Rain Water
2016-03-30 11:46
435 查看
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
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!
int trap(int* height, int heightSize) {
if(height==NULL)
return 0;
if (heightSize < 3)
return 0;
int k = 1, watersum = 0;
while (k < heightSize-1)
{
if (height[k] < height[k - 1])
{
int kk = k + 1;
int endhigh = height[k], endptr=-1;
while (kk < heightSize&&height[kk] < height[k - 1])
{
if (height[kk] > endhigh)
{
endptr = kk;
endhigh = height[kk];
}
kk++;
}
if (kk == heightSize)
{
if (endptr > 0)
{
for (int i = k; i < endptr; i++)
watersum += height[endptr] - height[i];
k = endptr+1;
}
else
k++;
}
else
{
for (int i = k; i < kk; i++)
watersum += height[k - 1] - height[i];
k = kk+1;
}
}
else
k++;
}
return watersum;
}
accepted
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!
int trap(int* height, int heightSize) {
if(height==NULL)
return 0;
if (heightSize < 3)
return 0;
int k = 1, watersum = 0;
while (k < heightSize-1)
{
if (height[k] < height[k - 1])
{
int kk = k + 1;
int endhigh = height[k], endptr=-1;
while (kk < heightSize&&height[kk] < height[k - 1])
{
if (height[kk] > endhigh)
{
endptr = kk;
endhigh = height[kk];
}
kk++;
}
if (kk == heightSize)
{
if (endptr > 0)
{
for (int i = k; i < endptr; i++)
watersum += height[endptr] - height[i];
k = endptr+1;
}
else
k++;
}
else
{
for (int i = k; i < kk; i++)
watersum += height[k - 1] - height[i];
k = kk+1;
}
}
else
k++;
}
return watersum;
}
accepted
相关文章推荐
- 柳峰微信公众平台开发教程企业号修改篇(企业菜单篇)
- 柳峰微信公众平台开发教程企业号修改篇(企业菜单篇)
- iOS quartzCore第二章——CAEAGLLayer简介
- Android中通过ViewHelper.setTranslationY实现View移动控制(NineOldAndroids开源项目)
- iOS应用运用设计模式中的Strategy策略模式的开发实例
- iOS 关于scrollView内部子控件的自动布局
- 柳峰微信公众平台开发教程企业号修改篇(AccessToken篇)
- 柳峰微信公众平台开发教程企业号修改篇(AccessToken篇)
- iOS开发常用的资源和资料
- Android用户注册界面
- ApplePay调研
- iOS 打电话 带提示框
- Android Loader使用详解
- iOSCoreAnimation动画系列教程(一):CABasicAnimation
- webview 实现滑动前进后退功能
- IOS开发--使用lookup table为图片添加滤镜
- ios调用百度、高德地图 导航功能
- Android中Handler的基本使用2
- iOS图片如何按比例显示
- IOS开发Swift键盘收起,键盘挡住输入模框的处理