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为底,选出两个坐标轴,使之间的水桶容量更大。
具体分析见代码
解题代码:
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++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性