leetcode 11 Container With Most Water
2016-01-28 01:17
459 查看
原题:
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.
大意:
给你n条线,任意挑两条,求以这两条线的x坐标为长度,最短的那条线给高度的面积的最大值。
解答:
之前上来两个循环遍历,结果超时了= =
考虑动态规划,结果想不出来= =
考虑用hash记录,结果还是想不出来= =
由于没有用hash,二分也不可能。只能有o(n)的算法,可以我没想到= =
看别人的题解知道要从两端遍历,判断两端那条线短,短的那条线前进。记录结果即可
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.
大意:
给你n条线,任意挑两条,求以这两条线的x坐标为长度,最短的那条线给高度的面积的最大值。
[code]class Solution { public: int maxArea(vector<int>& h) { int i=0,j=h.size()-1; int ans=-1; while(i<j) { ans=max(ans,min(h[i],h[j])*(j-i)); if(h[i]<h[j]) i++; else j--; } return ans; } };
解答:
之前上来两个循环遍历,结果超时了= =
考虑动态规划,结果想不出来= =
考虑用hash记录,结果还是想不出来= =
由于没有用hash,二分也不可能。只能有o(n)的算法,可以我没想到= =
看别人的题解知道要从两端遍历,判断两端那条线短,短的那条线前进。记录结果即可
相关文章推荐
- openssl使用SMTP从gmail发邮件
- nginx安装 nginx: [emerg] getpwnam(“www”) failed 错误
- WM_PAINT详解和WM_ERASEBKGND
- Run-Time Check Failure #2 - Stack around the variable 'xxx' was corrupted.
- LeetCode70. Climbing Stairs
- (译)Real-Time Hair Simulating And Rendering
- Splay hdu3487 Play with Chain
- main.xml
- Flash, Flex, Air, Flashplayer之间的相互关系是什么?
- explain 的用法
- ICMPPING failed
- INSTALL_FAILED_NO_MATCHING_ABIS
- leetcode70-Climbing Stairs(斐波那契数列)
- Jmeter测试接口稳定性BUG:Software caused connection abort: recv failed 错误介绍
- DevStack安装时报“download of get-pip.py failed”
- grails利用restful进行数据通信
- apache启动时提示httpd: Could not reliably determine the server's fully qualified domain name
- iPad air2 充不进去电
- PKIX path validation failed: mestamp check failed 错误
- 17996 Daily Cool Run(动态规划dp)