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;
        }
    }
    

      

         

           

          

        

  • 相关阅读:
    职业生涯起步不要去顶级公司
    discuz uc密码修改
    习惯决定成功与否
    世上没有理想的工作
    中山市慧海人力资源服务有限公司
    Codeforces Round #365 (Div. 2) B 前缀和
    Codeforces Round #365 (Div. 2) A 水
    tyvj 1067 dp 两次LIS(nlogn)
    Codeforces Round #303 (Div. 2) D 贪心
    Codeforces Round #303 (Div. 2) C dp 贪心
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6376410.html
Copyright © 2011-2022 走看看