编程语言
首页 > 编程语言> > LeetCode第11题:Container With Most Water(C++)详解

LeetCode第11题:Container With Most Water(C++)详解

作者:互联网

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.

在这里插入图片描述

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

题目解析:题目核心,即求取vector其中二个值中较小值,与该二个值下标间差的乘积;
解题思路:
1.数值都存储在vector中,其中的值及下标可随时获取;
2.设置二个下标,分别从左端和右端向当中遍历,分别标识为 i = 0;j = vector.size() - 1;
3.比较二个下标的高度值,分别为height[i] 和 height[j],取二者较小值 min(height[i],height[j]);
4.获取当前下标的Water值,即 result = min(height[i],height[j]) x (j - i);
5.当min(height[i],height[j]) 是height[i]时,i ++,左端下标向右移动,反之亦然;
6.如此遍历最大值为结果result。
解题代码:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int result = 0;//结果
        int i = 0,j = height.size() -1;//二个位置下标值
        while(i<j)//二端向中间遍历
        {
            int hght = min(height[i],height[j]);//比较较小值
            result = max(result,hght*(j-i));//较大值为结果
            while(i<j && hght == height[i])//较小值为左端下标,向右遍历
            {
                i++;
            }
            while(i<j && hght == height[j])//较小值为右端下标,向左遍历
            {
                j--;
            }
        }
        return result;
    }
};

性能:
在这里插入图片描述
总结:二个指针遍历是关键。

标签:11,下标,container,二个,C++,height,vector,result,Container
来源: https://blog.csdn.net/wanghuan1990519wha/article/details/90047341