LeetCode(11):盛最多水的容器 Container With Most Water(Java)

这道LeetCode问题要求找到能容纳最多水的两个垂直线段,可以通过固定宽度或宽度贪心策略求解。文章介绍了两种思路,并提供了相关算法的Java实现。
摘要由CSDN通过智能技术生成

2019.4.23 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

这道题是智力题,需要观察题目规律,容器既要够高,也要够宽。有两个思路:

思路一:固定宽度,找最大高度

对每一条线段i,找左右两端距离i最长的不小于i的长度的线段j。j作为长,i作为宽,ij构成的矩形是包含线段i的面积最大的矩形。

思路二:宽度贪心,找最大高度

设置left和right从两端逼近,每次计算其和较短边围成的矩形的面积,每次逼近移动较短边。逼近过程中最大的矩形面积即为所求。


传送门:盛最多水的容器

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 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器,且 n 的值至少为 2。

Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49


/**
 * 
 * @author ChopinXBP
 * 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 轴共同构成的容器可以容纳最多的水。
 * 说明:你不能倾斜容器,且 n的值至少为 2。
 *
 */

public class ContainerWithMostWater {
   

	public static void main(String[] args) {
   
		// TODO Auto-generated method stub
		int[] height = {
   
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值