您的位置:首页 > 大数据 > 人工智能

LeetCode之11_Container With Most Water

2016-06-16 22:18 447 查看
题目原文:

 

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.

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode