11. Container With Most Water
2016-04-02 00:25
351 查看
文章目录如下
(1)自己的思路
(2)自己的代码
(3)别人的思路
(4)别人的代码
(5)对比自己的不足之处
题目
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.
(1)自己的思路
a.由于木桶效应,桶的容量取决于最短的那块木板,在求桶的容积的时候(就是求面积),高要取短的那个边
b.遍历所有的"桶",分别求出容积进行比较,返回最大的那个容积。
(2)自己的代码
(3)别人的思路
从两边开始,往里缩小范围,其他思路跟我一样
(4)别人的代码
(5)对比自己的不足之处
我觉得我与别人最大的差别在于,我把所谓的桶一个一个的对待了,而不是将桶范围性的对待。虽然乍一看范围性的比较好像不能遍历所有的桶,所以求出的最大值是不准确的,但是仔细想来,却不是那么回事。因为桶的容积(面积)由宽与高决定着,要求最大的容积(面积)无非就是要求宽最大,高最大。按照这种从两边到中间的排除法,是不会漏掉面积最大的那个桶的。虽然我这种方法也能求出来,但是时间复杂度为n²,而别人的时间复杂度为n,不是一个数量级的,所以还是别人的思路更好!
(1)自己的思路
(2)自己的代码
(3)别人的思路
(4)别人的代码
(5)对比自己的不足之处
题目
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.
(1)自己的思路
a.由于木桶效应,桶的容量取决于最短的那块木板,在求桶的容积的时候(就是求面积),高要取短的那个边
b.遍历所有的"桶",分别求出容积进行比较,返回最大的那个容积。
(2)自己的代码
class Solution { public: int maxArea(vector<int>& height) { int maxArea = 0; int tmpArea = 0; int tmpHeight = 0; int tmpWidth = 0; for (int i = 0; i < height.size(); i++) for (int j = i; j < height.size(); j++) { tmpHeight = height[i] > height[j] ? height[j] : height[i]; tmpWidth = abs(j-i); tmpArea = tmpHeight*tmpWidth; if (tmpArea > maxArea) maxArea = tmpArea; } return maxArea; } };
(3)别人的思路
从两边开始,往里缩小范围,其他思路跟我一样
(4)别人的代码
class Solution { public: int maxArea(vector<int> &height) { int start = 0; int end = height.size() - 1; int result = INT_MIN; while (start < end) { int area = min(height[end], height[start]) * (end - start); result = max(result, area); if (height[start] <= height[end]) { start++; } else { end--; } } return result; } };
(5)对比自己的不足之处
我觉得我与别人最大的差别在于,我把所谓的桶一个一个的对待了,而不是将桶范围性的对待。虽然乍一看范围性的比较好像不能遍历所有的桶,所以求出的最大值是不准确的,但是仔细想来,却不是那么回事。因为桶的容积(面积)由宽与高决定着,要求最大的容积(面积)无非就是要求宽最大,高最大。按照这种从两边到中间的排除法,是不会漏掉面积最大的那个桶的。虽然我这种方法也能求出来,但是时间复杂度为n²,而别人的时间复杂度为n,不是一个数量级的,所以还是别人的思路更好!
相关文章推荐
- 阶梯博弈(Stair Nim)
- leetcode 172. Factorial Trailing Zeroes
- rails中使用ajax
- 领域驱动设计(Domain Driven Design)参考架构详解
- leetcode 每日一题 172. Factorial Trailing Zeroes
- tail -F查看线上日志
- Run-Time Check Failure #0 错误
- leetcode 70. Climbing Stairs
- 【HDU】 1023 Train Problem II
- 解决maillog文件删除后无法重建的问题
- opencv_traincascade问题
- AIDL的Binder框架
- 出现( linker command failed with exit code 1)错误总结
- 【HDU】 1022 Train Problem I
- 手动执行failover
- 朴素贝叶斯(naive bayes)
- SendMail发邮件
- RAID技术介绍和总结
- kail新手安装
- 【HDU】 1021 Fibonacci Again