本文共 899 字,大约阅读时间需要 2 分钟。
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.
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
使用双指针,一个从头一个从尾,但是具体怎么控制指针的移动?谁大移动谁?有点想法,但是很模糊
感觉已经跟答案的想法很接近了!其实自己再多梳理一下就能做出来了
这里的思想是,因为往内移动,长是越来越短的,所以需要移动指针去寻找更高的地方public class Solution { public int maxArea(int[] height) { int maxarea = 0, l = 0, r = height.length - 1; while (l < r) { maxarea = Math.max(maxarea, Math.min(height[l], height[r]) * (r - l)); if (height[l] < height[r]) l++; else r--; } return maxarea; }}
转载地址:http://ffqvb.baihongyu.com/