zoukankan      html  css  js  c++  java
  • leetcode : Container With Most Water

    Container With Most Water

    Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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 and n is at least 2.

    思路: two pointers

    两根指针,分别指向头尾,若height[i] < height[j], 则i++, 否则j--.  O(n)时间复杂度。

    原理: 木桶原理的特点是取短板。 因为水的最大高度只能到短板,否则会溢出。

        为什么height[i] < height[j],i++?

    证明: 反证法。

          假定height[i] < height[j],  取任意k, 使得 i < k < j。 

           => (j - i) * height[i]  > (k - i) * min(height[i], height[k])

           = >  移动j指针,只会得到比当前更小的容量。 因为 (j - i) >> (k - i), height[i] >= min(height[i], height[k]) 

           =>   因此,若移动i,则有可能得到比当前更大的容量。

    public class Solution {
        public int maxArea(int[] height) {
            if(height == null || height.length < 2) {
                return 0;
            }
            
            int i = 0;
            int j = height.length - 1;
            int max = 0;
            
            while(i < j) {
                if(height[i] < height[j]) {
                    int tmp = (j - i) * height[i];
                    max = Math.max(max,tmp);
                    i++;
                } else {
                    int tmp = (j - i) * height[j];
                    max = Math.max(max,tmp);
                    j--;
                }
            }
            return max;
        }
    }
    

      

         

           

          

        

  • 相关阅读:
    三种方式重启NGINX 简单
    转MongoDB、HandlerSocket和MySQL性能测试及其结果分析 简单
    php ini_set post_max_size,upload_max_filesize 简单
    grep 命令 简单
    ANSI,GBK,UTF8,UTF16LE,UTF16BE 简单
    提升工作效率软件 简单
    会议记录 简单
    第一章 :zabbix监控
    第七章 :分布式监控与SNMP监控
    linux系统安装SNMP(可用)
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6376410.html
Copyright © 2011-2022 走看看