zoukankan      html  css  js  c++  java
  • Java [leetcode 11] Container With Most Water

    问题描述:

    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.

    解题思路:

    这道问题还是比较简单的,首先要理解它的意思,整个容器的高度是由较短的那根线决定的。然后从两边分别开始往中间收缩,对短的那根线进行往里收缩。这是容器的高度是由短的那根线决定的,那么当对高线往中间收缩时候,面积是在逐渐减小的,所以应该对矮的那根线进行收缩。

    代码如下:

    public class Solution {
        public int maxArea(int[] height) {
    		int left = 0;
    		int right = height.length - 1;
    		int maxArea = (right - left) * Math.min(height[left], height[right]);
    		int temp;
    		
    		while(left < right){
    			if(height[left] < height[right]){
    				left++;
    			}
    			else{
    				right--;
    			}
    			temp = (right - left) * Math.min(height[left], height[right]);
    			if(temp > maxArea)
    				maxArea = temp;
    		}
    		return maxArea;
    	}
    }
    
  • 相关阅读:
    API下载文件
    c# 测试网络连接
    C# Word 插入签名图片
    c# word文档合并
    c# 文件筛选
    e
    基本初等函数(Basic elementary function)
    前端性能优化学习
    解决点击穿透的最佳实践
    ObjectARX通过选定的实体获取所有组名示例
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4456930.html
Copyright © 2011-2022 走看看