LeetCode :: Container With Most Water

来源:互联网 发布:淘宝提交多个订单 编辑:程序博客网 时间:2024/06/05 17:44

题目如下:

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.

一、最简单粗暴的做法,遍历所有可能(i,j),计算出maxArea,时间复杂度O(N2)。


二、思考一下,从两端开始往中间遍历,设i = 0, j = height.size() - 1;   由于是短板决定计算出的面积大小,所以当让坐标往中间走的时候(宽度是递减的),必须移动短的一端。这样才有希望让面积增大,不然的话,由于短板限制,面积肯定随着宽度的减少而递减。

代码如下:

class Solution {public:    int maxArea(vector<int> &height) {        int area = 0, Max = 0;        int i = 0, j = height.size() - 1;        while (i < j){            if (height[i] > height[j]){                area = height[j] * (j - i);                j--;            }            else{                area = height[i] * (j - i);                i++;            }            if (area > Max)                Max = area;        }        return Max;    }};


0 0
原创粉丝点击