LeetCode11-Container With Most Water

来源:互联网 发布:手机淘宝店铺链接在哪 编辑:程序博客网 时间:2024/05/12 16:45

【题目】

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.

【思路】

两条垂线与x轴所围成的区域容水的多少与两条垂线中的短边和两个垂线间的距离有关;

分别从i=0 和j = array.length-1处同时向中间检索,计算当前状态并与最佳状态进行比较,优于则更新;

从两条垂线中选择较短的一边向内推动,成为下一个状态,直至两条垂线重合;

【Java代码】

public class Solution_11_container_with_most_water {public int maxArea(int[] height){int result = 0;int i = 0, j = height.length - 1;while(j > i){int area = (height[j] > height[i] ? height[i]:height[j])*(j-i);result = area>result?area:result;if(height[j]>height[i])i++;else j--;}return result;}}


0 0
原创粉丝点击