Container with most water_Leetcode_#11

来源:互联网 发布:openstack网络架构 编辑:程序博客网 时间:2024/06/04 18:25

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;    }}
0 0
原创粉丝点击