【leetcode】【11】Container With Most Water

来源:互联网 发布:淘宝一般违规48分申诉 编辑:程序博客网 时间:2024/05/17 05:13

一、问题描述

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

二、问题分析

这是一维数组的遍历问题。而再处理遍历的时候双指针是非常常用的方法。该题显然也需要一左一右两个指针来遍历。还有一点需要明确的就是短板决定容器的容量。

三、Java AC代码

public int maxArea(int[] height) {int max = 0;if (height == null || height.length < 2) {return max;}int left = 0, right = height.length - 1;while (left < right) {int tmp = Math.min(height[left], height[right]) * (right - left);if (tmp > max) {max = tmp;}if (height[right]<height[left]) {int key = height[right];while(--right > left && height[right] < key);}else {int key = height[left];while(++left < right && height[left] < key);}}return max;}



0 0
原创粉丝点击