• 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;
    	}
    }
    
  • 相关阅读:
    QNET弱网测试工具
    echart
    数组按照一大一小打乱排列
    根据环境开启 vconsole
    时间戳在ios上面显示NAN Bug
    去除字符串中html标签
    ios 上 复选框背景黑边bug
    echarts配置项说明
    JS 数据处理技巧及小算法
    js中最常用的几种遍历数据方法
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4456930.html
Copyright © 2020-2023  润新知