[LeetCode-Algorithms-11] "Container With Most Water" (2017.10.2-WEEK5)

来源:互联网 发布:新溪岛蜂蜜 知乎 编辑:程序博客网 时间:2024/06/08 18:48

题目链接:Container With Most Water


  • 题目描述:

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.

Note: You may not slant the container and n is at least 2.


(1)思路:两个指针分别从容器的左右向中间移动直到相遇,检查移动的过程中形成容量最大的容器。

(2)代码:

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

(3)提交结果:

·这里写图片描述

原创粉丝点击