LeetCode——11. Container With Most Water

来源:互联网 发布:网络歌曲经典老歌 编辑:程序博客网 时间:2024/06/10 19:41

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 and n is at least 2.


翻译

给定n个非负整数a1,a2,...,an,其中每个代表一个点坐标(i,ai)。n个垂直线段例如线段的两个端点在(i,ai)和(i,0)。找到两个线段,与x轴形成一个容器,使其包含最多的水。备注:你不必倾倒容器。
题目的意思是,数组中的每个数对应一条线段的长度,索引对应x坐标,两个索引可以组成一个底部的宽,高度就是前面所说的线段的长度,而既然是要盛水,高度就是两个线段中较短的一个。


思路:从前后两端开始依次算面积大小。每次把较小的那条边换掉,向中间逼进。这样时间复杂度就是o(n)

public class Solution {    public int maxArea(int[] height) {        if(height.length==0)return 0;                int left = 0;        int right = height.length-1;        int area =0;        while(left<right){        int h ;        int temp;        if(height[left]<height[right])h=height[left];        else {    h=height[right];}        temp = (right-left)*h;        if(area<temp)area = temp;        if(height[left]<height[right])left++;        else{        right--;        }        }        return area;    }}


0 0
原创粉丝点击