[LeetCode]99. Container with Most Water最大容积
2015-12-05 11:35
519 查看
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,a1),(2,a2),...,(n,an),这些点各自与(1,0),(2,0),...,(n,0)连成一条条垂直线,任取两条(i,ai)和(j,aj),与(i,j)组成一个容器,求能够得到的最大容积的(i,ai)和(j,aj)。
解法1:暴力破解,两层循环求出所有容器的容积,然后取最大值。Time Limit Exceeded
解法2:题目提示使用两个指针。两个指针指向数组两端,计算出容积并更新结果;然后比较左右直线的高度,将高度较小的那个移动一步;直到两个指针相遇。
Note: You may not slant the container.
Subscribe to see which companies asked this question
在第一象限存在点(1,a1),(2,a2),...,(n,an),这些点各自与(1,0),(2,0),...,(n,0)连成一条条垂直线,任取两条(i,ai)和(j,aj),与(i,j)组成一个容器,求能够得到的最大容积的(i,ai)和(j,aj)。
解法1:暴力破解,两层循环求出所有容器的容积,然后取最大值。Time Limit Exceeded
class Solution { public: int maxArea(vector<int>& height) { int n = height.size(), maxContain = 0; for (int i = 0; i < n - 1; ++i) { for (int j = i + 1; j < n; ++j) { int minHeight = min(height[i], height[j]); int contain = (j - i) * minHeight; if (contain > maxContain) maxContain = contain; } } return maxContain; } };
解法2:题目提示使用两个指针。两个指针指向数组两端,计算出容积并更新结果;然后比较左右直线的高度,将高度较小的那个移动一步;直到两个指针相遇。
class Solution { public: int maxArea(vector<int>& height) { int left = 0, right = height.size() - 1, maxContain = 0; while (left < right) { maxContain = max(min(height[left], height[right]) * (right - left), maxContain); if (height[left] < height[right]) ++left; else --right; } return maxContain; } };
相关文章推荐
- CreateThread和_beginthread区别及使用http://blog.csdn.net/wxq1987525/article/details/6620210
- HDU 2674:N!Again【数学】
- 内存泄漏 http://baike.baidu.com/link?url=xs_CTQcDnYkB4fXPOC0-1nAS666wXdUtiUxmP9udmWq4rYFOq4Ij2CElO-iVAjY
- Failed to open/create the internal network Vagrant on Windows10
- maven项目配置Project Facets时further configuration available不出来问题
- wait()和sleep()的区别
- 4-4 Cube Painting
- 你眼中的async/await是什么样的?
- UltraISO 9.6.5.3237
- Daily Scrum - 12/04
- hdoj1032The Snail
- MHA自动Failover过程解析
- [ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-t
- 请求的报的一般错误:One or more post-processing actions failed. Consult the OPP service log for details.
- Wait 和Pulse 等待和暂停的信号
- LeetCode 172 Factorial Trailing Zeroes
- [LeetCode] Container With Most Water 简要分析
- [LeetCode] Container With Most Water 简要分析
- 【LeetCode】219 Contains Duplicate II
- AC 与 GLPI的MAC地址自动同步脚本 expect mail ver4.0【最新】