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 = {