1.题目 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.
2.解法 思路:从首部和尾部开始遍历,选取两者高度较小的那一个来乘两者之间的距离得到一个面积值,更新max值,且较小的那一端网中间移动。 时间复杂度:O(N)
public class Solution { public int maxArea(int[] height){ int max = 0; int size = height.length; int lhs = 0, rhs = size - 1; while(lhs < rhs){ int temp; if(height[lhs] < height[rhs]){ temp = (rhs -lhs) * height[lhs++]; }else{ temp = (rhs -lhs) * height[rhs--]; } max = Math.max(max, temp); } return max; } }