[LeetCode]Container With Most Water

来源:互联网 发布:word数据透视表 编辑:程序博客网 时间:2024/05/21 10:39

[LeetCode]Container With Most Water

题目描述

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.

解题思路

  • 用两个变量记录水桶的左边缘(left)和右边缘(right);
  • 达到最优解时,两个边缘都必须满足一个至关重要的条件——边缘外侧不能有更高的木板,因为如果外侧有更高的木板,则可用更高的木板作为边缘替换当前的边缘木板,得到更大的容积;
  • 所以可以考虑从两端向中间遍历,如果遍历的当前的木板的外侧有更高的木板,则可以直接跳过不必计算面积;

代码

public class ContainerWithMostWater {    public static int maxArea(int[] height) {        int left = 0;         int right = height.length-1;        int area = 0;        int leftmax = left, rightmax = right;        while(left < right) {            int temparea = (right-left) * (Math.min(height[left], height[right]));            if(temparea > area) area = temparea;            if(height[left] > height[leftmax]) leftmax = left;            if(height[right] > height[rightmax]) rightmax = right;            if(height[left] < height[right]) {                left++;                while(height[left] < height[leftmax]) left++;            }            else {                right--;                while(height[right] < height[rightmax]) right--;            }        }        return area;    }    public static void main(String[] args) {        int[] height = {1, 2, 1};        System.out.println(maxArea(height));    }}

感想

啊。。。。代码小弱的第一篇技术相关博客@@#¥%……&*
medium难度的题感觉想清楚了写起来还是很快的木哈哈

本题说到底还是一个“双指针”问题,双指针的使用可以将原本需要两层嵌套循环的问题降低到只用一次循环即可解决。

0 0