Container With Most Water
2015-07-17 13:56
211 查看
题目:
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.
给定一个非负数组height, 其中的第i位与第i位的值(i, height[i])是坐标平面上的一个点,它与x轴做垂直线,这样就形成了i个垂直于x轴的线,假设这些是盛水的段短,求任意两个短板间水的容量最大值。
使用双层循环实现,但当数组很大时就 Time limited Exceeded。
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.
给定一个非负数组height, 其中的第i位与第i位的值(i, height[i])是坐标平面上的一个点,它与x轴做垂直线,这样就形成了i个垂直于x轴的线,假设这些是盛水的段短,求任意两个短板间水的容量最大值。
使用双层循环实现,但当数组很大时就 Time limited Exceeded。
public static int maxArea(int[] arr){ int end=arr.length-1,max=0,temp=0; for(int i=0;i<end;i++){ for(int j=i;j<end;j++){ temp=Math.min(arr[i], arr[j])*(j-i); max=max>temp?max:temp; } } return max; }解决方法:取最左边的为left,最右边的为right,所有可能比这种大的情况只能是这两个高度较小的那一端向中间移动。一直循环这个动作,最大值肯定在其中。
public static int maxArea(int[] height) { int start=0,end=height.length-1,max=0,temp=0; while(start<end){ temp=Math.min(height[start], height[end])*(end-start); max=max>temp?max:temp; if(height[start]>height[end]) end--; else start++; } return max; }
相关文章推荐
- magento Service Temporarily Unavailable
- sleep() 和 wait() 的区别
- ACM--Doing Homework again(贪心算法)
- cvs报错: socket exception recv failed
- C main的反汇编简单介绍
- Baidu Map开发示例
- Autoconf中AC_CHECK_LIB依赖第三方库时FAIL
- Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE无法安装错误解决方案
- How-to: enable fair scheduler in hadoop
- Jmeter性能测试NoHttpResponseException (the target server failed to respond)
- 启动Genymotion时报错Failed to initialize backend EGL display
- Pick a Self-Contained Set of Tablespaces(自包含)
- fail to register notify:Error Domain=NSCocoaErrorDomain Code=3000 "未找到应用程序的“aps-environment”的授权字符串"
- Gem总结
- Baidu地图之removeEventListener失效问题
- gtk程序运行报 main_loop!=NULL 错误的解决办法
- gtk程序运行报 main_loop!=NULL 错误的解决办法
- gtk程序运行报 main_loop!=NULL 错误的解决办法
- 奔跑吧,飞邮!TurboMail全面进军移动邮件系统
- Partition(hdu4651)2013 Multi-University Training Contest 5