llllmz

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

42. 接雨水C

因为还是双指针的题目。

我想到的短板效应,看两头,能接住的水也就是取决于最短的一方。

每次看两头后,在里面找比最短还短的地方,那个就是有水的地方。找到水后在把它填平,防止重复找到。然后两头往中间靠就行了。

int min(int i,int j){
if(i>j) return j;
return i;
}
int findsum(int* height,int head,int tail,int t){
if(t==0) return 0;
int sum=0;
for(;head<=tail;head++){
if(height[head]<t){
sum+=t-height[head];
height[head]=t;
}
}
return sum;
}
int trap(int* height, int heightSize) {
int head=0,tail=heightSize-1;
while(height[head]==0 && head<tail) head++;
while(height[tail]==0 && tail>head) tail--;
int sum=0;
while(head <tail){
int t=min(height[head],height[tail]);
sum+=findsum(height,head+1,tail-1,t);
if(height[head]==height[tail]){
head++;
tail--;
while(head<tail && height[head]<=height[head-1]) head++;
while(head<tail && height[tail]<=height[tail+1]) tail--;
}else if(height[head] <height[tail]){
head++;
while(head<tail && height[head]<=height[head-1]) head++;
}else{
tail--;
while(head<tail && height[tail]<=height[tail+1]) tail--;
}
}
return sum;
}

结果:懒得优化了。等考上研究生了。在提高要求把。目前还是把题目能解出来的阶段。

posted on   神奇的萝卜丝  阅读(5)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示