H*s
2 楼
记得在哪里看过,只用从左到右扫描一遍,每次都把当前的bar向左所能trap的容量记
下。
关键是要用一个stack来记录已处理过的bars,没时间写代码了,你可以自己试着写。
下。
关键是要用一个stack来记录已处理过的bars,没时间写代码了,你可以自己试着写。
w*o
3 楼
这解法是O(n),空间是O(1):
大概的意思就是用左右两个指针,比较两个指针所指的值,从小的那个往中间移,移的
过程中要么增加maxL(或者maxR),要么tap water。直道两个指针相遇,其实两个相
遇在最大值。
if (bars == null || bars.length <= 2)
return 0;
int area = 0;
int l = 1, r = bars.length - 2;
int maxL = bars[0], maxR = bars[bars.length - 1];
while(l <= r)
{
if (maxL <= maxR)
{
if (bars[l] < maxL)
area += maxL - bars[l];
else
maxL = bars[l];
l++;
}
else
{
if (bars[r] < maxR)
area += maxR - bars[r];
else
maxR = bars[r];
r--;
}
}
return area;
大概的意思就是用左右两个指针,比较两个指针所指的值,从小的那个往中间移,移的
过程中要么增加maxL(或者maxR),要么tap water。直道两个指针相遇,其实两个相
遇在最大值。
if (bars == null || bars.length <= 2)
return 0;
int area = 0;
int l = 1, r = bars.length - 2;
int maxL = bars[0], maxR = bars[bars.length - 1];
while(l <= r)
{
if (maxL <= maxR)
{
if (bars[l] < maxL)
area += maxL - bars[l];
else
maxL = bars[l];
l++;
}
else
{
if (bars[r] < maxR)
area += maxR - bars[r];
else
maxR = bars[r];
r--;
}
}
return area;
M*e
4 楼
thanks
【在 w***o 的大作中提到】
: 这解法是O(n),空间是O(1):
: 大概的意思就是用左右两个指针,比较两个指针所指的值,从小的那个往中间移,移的
: 过程中要么增加maxL(或者maxR),要么tap water。直道两个指针相遇,其实两个相
: 遇在最大值。
: if (bars == null || bars.length <= 2)
: return 0;
: int area = 0;
: int l = 1, r = bars.length - 2;
: int maxL = bars[0], maxR = bars[bars.length - 1];
: while(l <= r)
【在 w***o 的大作中提到】
: 这解法是O(n),空间是O(1):
: 大概的意思就是用左右两个指针,比较两个指针所指的值,从小的那个往中间移,移的
: 过程中要么增加maxL(或者maxR),要么tap water。直道两个指针相遇,其实两个相
: 遇在最大值。
: if (bars == null || bars.length <= 2)
: return 0;
: int area = 0;
: int l = 1, r = bars.length - 2;
: int maxL = bars[0], maxR = bars[bars.length - 1];
: while(l <= r)
H*s
5 楼
这个解法更简洁而且空间是O(1), wasco还是牛啊!
【在 w***o 的大作中提到】
: 这解法是O(n),空间是O(1):
: 大概的意思就是用左右两个指针,比较两个指针所指的值,从小的那个往中间移,移的
: 过程中要么增加maxL(或者maxR),要么tap water。直道两个指针相遇,其实两个相
: 遇在最大值。
: if (bars == null || bars.length <= 2)
: return 0;
: int area = 0;
: int l = 1, r = bars.length - 2;
: int maxL = bars[0], maxR = bars[bars.length - 1];
: while(l <= r)
【在 w***o 的大作中提到】
: 这解法是O(n),空间是O(1):
: 大概的意思就是用左右两个指针,比较两个指针所指的值,从小的那个往中间移,移的
: 过程中要么增加maxL(或者maxR),要么tap water。直道两个指针相遇,其实两个相
: 遇在最大值。
: if (bars == null || bars.length <= 2)
: return 0;
: int area = 0;
: int l = 1, r = bars.length - 2;
: int maxL = bars[0], maxR = bars[bars.length - 1];
: while(l <= r)
相关阅读
有人做过Caliper Assessment 吗?(包子答谢)帮忙看个题一个猎头公司发的2012 Q3的热门IT技术HR打电话推迟了PHONE INTERVIEW可是再也没消息了?急问达人xdjm: 140 才批, 结果上周被laid off请问有人有pinterest phone interview 面经吗?好吧,微软11/15,11/16 STB Hiring Event 的同学可不可以汇报一下?Amazon On-site ,kindle组有什么要特别注意的地方么?+前两轮电面面经又面了一上午,M家的,大家进来做题问个弱智问题:leetcode上的题答案只能一道一道找吗bonus 和relocation fee 是在offer letter 里面一起的吗?老题重提:反转字符串请问招聘信息里只写要本科生的phd还要申请么?大家一般怎么了解一个小公司请高手帮助几道 perl 编程题下周一早上9点MS电面,求指教有谁知道scopely.com 这家公司的?分享今天做的一道基础题phd码工的困惑问个非常严肃的问题 签了offer在面试 是不是素质非常低