LeetCode解题报告--Container With Most Water
2015-08-13 17:37
656 查看
题目:最大的盛水容器
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.
原题链接地址:https://leetcode.com/problems/container-with-most-water/
分析:题意是给定长度为n整型数组height;分别构成(1,height[1]),(2,height[2]),….(n,height
)坐标点,找出两个点分别过这些点做垂直X轴的垂线,以及连接这两个点,与X轴构成长方形容器,求该容器的最大值!
通过两个变量leftHeiht,rightHeight分别指向数组height的最左端和最右端,这样宽度最大,当缩小宽度,则需要寻找较大的高度。
做简单证明
Java 代码:(accepted)
测试结果:
相关代码放在个人github:https://github.com/gannyee/LeetCode/tree/master/src
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.
原题链接地址:https://leetcode.com/problems/container-with-most-water/
分析:题意是给定长度为n整型数组height;分别构成(1,height[1]),(2,height[2]),….(n,height
)坐标点,找出两个点分别过这些点做垂直X轴的垂线,以及连接这两个点,与X轴构成长方形容器,求该容器的最大值!
通过两个变量leftHeiht,rightHeight分别指向数组height的最左端和最右端,这样宽度最大,当缩小宽度,则需要寻找较大的高度。
做简单证明
Java 代码:(accepted)
public class ContainerWithMostWater { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] a = { 1, 4, 5, 6, 3, 8, 9, 12, 45 }; System.out.println("Max Area is : " + maxArea(a)); int[] a1 = { 12,45,32,78,11,23,14 }; System.out.println("Max Area is : " + maxArea(a1)); int[] a2 = { 90,34,45,21,43,32}; System.out.println("Max Area is : " + maxArea(a2)); } public static int maxArea(int[] height) { int maxArea = 0; // The max area int leftHight = 0; int rigtHight = height.length - 1; while (leftHight < rigtHight) { //Calculate the max area maxArea = Math.max(maxArea, (rigtHight - leftHight) * Math.min(height[leftHight], height[rigtHight])); //Because of cast effect, hence choose shortest height if (height[leftHight] > height[rigtHight]) rigtHight--; else leftHight++; //System.out.println("Left: " + height[leftHight] + " " + leftHight + " Right: " + height[rigtHight] + " " + rigtHight); //System.out.println("Max Area: " + maxArea); } return maxArea; } }
测试结果:
Max Area is : 30 Max Area is : 92 Max Area is : 172
相关代码放在个人github:https://github.com/gannyee/LeetCode/tree/master/src
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- RPC failed; result=22, HTTP code = 411
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树