zoukankan      html  css  js  c++  java
  • 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.

    分析

    题目在时间复杂度O(n2)下一个两次循环遍历即可,但需要时间复杂度O(n)的下完成,通过分析,可以采用左右夹逼的方式来做,如果说左边数大于右边的数,则右边向左偏移一位,否则左边向右偏移一位

    代码

    package com.lilei.myes.es.pack1108;
    
    public class ContainerWithMostWater {
    
    	public static void main(String[] args) {
    		System.out.println(cwmw(new int[]{3,2,3,4,5}));
    
    	}
    	static int cwmw(int[] array){
    		int area = 0;
    		
    		int left = 0;
    		
    		while(array[left] <=0){
    			left++;
    		}
    		
    		int right = array.length-1;
    		
    		while(array[right] <=0){
    			right--;
    		}
    		
    		while(left < right){
    			int height = array[left]>array[right]?array[right] : array[left];
    			
    			area = Math.max(area, height * (right - left));
    			
    			if (array[left] > array[right])
    				array[left] = right--;
    			else
    				array[left] = left++;
    		}
    		
    		return area;
    	}
    
    }
    

      

  • 相关阅读:
    单例模式(Singleton)
    cdlinux
    android 去锯齿
    ide
    图片加载内存溢出
    android AlertDialog 弹出窗
    找回 文件下载 ie 窗口
    javac 多个jar文件 用封号 隔开
    android 模拟按钮点击
    android 加载多个图片 内在溢出的问题
  • 原文地址:https://www.cnblogs.com/lilei2blog/p/7803788.html
Copyright © 2011-2022 走看看