当前位置: 首页 > news >正文

Leetcode-42. Trapping Rain Water [C++][Java]

目录

一、题目描述

二、解题思路

【C++】

【Java】


Leetcode-42. Trapping Rain Waterhttps://leetcode.com/problems/trapping-rain-water/description/

一、题目描述

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) 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.

Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9

Constraints:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

二、解题思路

【C++】

class Solution {
public:
    int trap(vector<int>& height) {
        if (height.size() == 0) {
            return 0;
        }
        int left = 0, right = height.size() - 1;
        int leftMax = height[left], rightMax = height[right], res = 0;
        while (left < right) {
            if (height[left] < height[right]) {
                res += leftMax - height[left++];
                leftMax = max(leftMax, height[left]);
            } else {
                res += rightMax - height[right--];
                rightMax = max(rightMax, height[right]);
            }
        }
        return res;
    }
};

【Java】

class Solution {
    public int trap(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }
        int left = 0, right = height.length - 1;
        int leftMax = height[left], rightMax = height[right], res = 0;
        while (left < right) {
            if (height[left] < height[right]) {
                res += leftMax - height[left++];
                leftMax = Math.max(leftMax, height[left]);
            } else {
                res += rightMax - height[right--];
                rightMax = Math.max(rightMax, height[right]);
            }
        }
        return res;
    }
}

相关文章:

  • 能否在delete一个指针后继续使用它以及原因
  • MQTT实现智能家居------3、源码分析(超详细)
  • JavaScript中的call方法相关知识点
  • ZLG嵌入式笔记 | 为什么你的网卡工作会不正常?(上
  • 鸿蒙学习-
  • ctf网络安全题库 ctf网络安全大赛答案
  • JSP学习
  • MybatisPlus-注解
  • 【Python基础】Python 环境安装 Win10
  • 爬虫第九篇-结束爬虫循环
  • 【论文解读】《Training Large Language Models to Reason in a Continuous Latent Space》
  • STL容器终极解剖:C++ vector源码级实现指南 | 从内存分配到异常安全的全流程避坑
  • 【Git】远程操作
  • 进程概念、PCB及进程查看
  • 基于SpringBoot的校园消费点评管理系统
  • 从.m3u8到.mp4:使用批处理脚本完成视频处理的完整指南
  • 微服务架构概述及创建父子项目
  • MongoDB 简介
  • Spring Boot3+Vue2极速整合:10分钟搭建DeepSeek AI对话系统
  • 侯捷 C++ 课程学习笔记:四个层面基本用法
  • 深圳平湖网站建设公司/长沙新媒体营销
  • 推荐一些做网站网络公司/怎么做网络销售
  • 变身 变装 wordpress/广州推广优化
  • 旅游网站改版方案/长沙关键词优化平台
  • 学院网站建设新闻简报/微信引流获客软件
  • 微信微网站是什么/百度推广seo效果怎么样