LeetCode之11_Container With Most Water

题目原文:

 

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.

Subscribe to see which companies asked this question

 

题意分析:

以1为单位间隔,给出坐标轴1到n上的隔板高度,以x为底,选出两个坐标轴,使之间的水桶容量更大。

具体分析见代码

 

 

 

解题代码:

 

//传入一个序列,分别对应横坐标从1到n的高度,求任意两个高度作为围墙构造的容器能够盛放的最大水量
//waterCapcity = (j-i)*min(h(j),h(i));
//i,j为两个点的横坐标,h(j)为传入的j点高度
//以第一个点和最后一个点作为起始情况进行考虑,此时(j-i)最大,考虑两个高度的情况
//若h(i)<h(j),此时的容量为i的高度h(i)乘以宽度(j-i);以下有两种移动方法
//1.  把右侧的边往左移,此时可能造成h(j)的改变。若h(j)变大:aterCapcity = (j-i)*min(h(j),h(i));  h(i)还是小于h(j),而(j-i)变小,则必定导致结果变小; 若h(j)变小,同理,结果只可能变小。所以,此情况下必然导致蓄水量变小。
//2.  把左侧的边往右移,此时可能造成h(i)的改变。因为在当前情况下h(i)在和h(j)的比较中属于较小的一方,改变后。可能造成min(h(j),h(i))的变大或者变小,虽然(j-i)变小,但是结果有可能会变大。
//h(i)>h(j)时分析情况相同


#include <iostream>
#include <vector>
#include <cmath>
using namespace std;



class Solution {
public:
	int maxArea(vector<int>& height) {

		int nContWater = 0;
		int nTemp;
		int i=0,j=0;
		for (i=0,j=height.size()-1; i<j; )
		{
			if (height[i]<height[j])
			{
				nTemp = height[i]*(j-i);
				i++;
			}
			else
			{
				nTemp = height[j]*(j-i);
				j--;
			}

			if (nTemp>nContWater)
			{
				nContWater = nTemp;
			}
		}

		return nContWater;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值