LeetCode11——Container With Most Water

来源:互联网 发布:2017淘宝618活动时间 编辑:程序博客网 时间:2024/05/16 23:45

常写算法,多动脑,不会老!

题目描述:

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.

题目我就不翻译啦!都是明日之星!!

解题思路:

这题如果暴力破解,估计凶多吉少,笔者没有试过,估计会报超时!思路很简洁,也很高效。采用从两头往中间靠的思路,面积计算公式为:

currentArea = (right - left)*min(height[left],height[right]);

如果能理解到这,那本题就算是搞定了!

贴一个非常简洁高效的 C++ 代码

int maxArea(vector<int>& height) {    int lengthHeight = (int)height.size();    int left = 0;    int right = lengthHeight - 1;    int currentArea = 0;    int maxarea = 0;    while (left < right) {        currentArea = (right - left)*min(height[left],height[right]);        maxarea = max(currentArea,maxarea);        if (height[left] < height[right]) {            left ++;        } else {            right --;        }    }    return maxarea;}

代码效率:
这里写图片描述

原创粉丝点击