前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 11. Container With Most Water题目分析代码

LeetCode 11. Container With Most Water题目分析代码

作者头像
desperate633
发布2018-08-22 12:41:26
2600
发布2018-08-22 12:41:26
举报
文章被收录于专栏:desperate633

Given n non-negative integers *a1 *, *a2 *, ..., an , where each represents a point at coordinate (i, ai ). n vertical lines are drawn such that the two endpoints of line i is at (i, ai ) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note: You may not slant the container and n is at least 2.

题目

给定 n 个非负整数 a1, a2, ..., an, 每个数代表了坐标中的一个点 (i, ai)。画 n 条垂直线,使得 i 垂直线的两个端点分别为(i, ai)和(i, 0)。找到两条线,使得其与 x 轴共同构成一个容器,以容纳最多水。 注意事项 容器不可倾斜。 样例 给出[1,3,2], 最大的储水面积是2

分析

用两根指针一头一尾,分别计算面积,然后选取高度小的那边向中间移动,因为这样才可能存在更大的面积,更新最大的面积,最后就是结果。

Paste_Image.png

代码

代码语言:javascript
复制
public class Solution {
    /**
     * @param heights: an array of integers
     * @return: an integer
     */
    int computeArea(int left, int right,  int[] heights) {
        return (right-left)*Math.min(heights[left], heights[right]);
    }
    
    public int maxArea(int[] heights) {
        //两根指针,一头一尾计算,短的那根指针向中间移动,因为只有这种情况才存在更大的情况
        int left = 0, right = heights.length-1;
        int res = 0;
        
        while(left < right) {
            res = Math.max(res, computeArea(left,right,heights));
            if(heights[left] < heights[right]) {
                left++;
                //如果小于则不必要计算,直接跳过
                while(heights[left] <= heights[left-1] && left<right)
                    left++;
            }
            else {
                right--;
                while(heights[right] <= heights[right+1] && left <right)
                    right--;
            }
        }
        return res; 
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017.03.22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 分析
  • 代码
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档