zoukankan      html  css  js  c++  java
  • 03_02_leetcode_11_盛最多的水

    1.题目描述

    给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

    说明:你不能倾斜容器

    示例 1:

    输入:[1,8,6,2,5,4,8,3,7]
    输出:49
    解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
    示例 2:

    输入:height = [1,1]
    输出:1

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/container-with-most-water
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    2.思路介绍:双指针

    面积公式 S(i, j) = min(h[i], h[j]) × (j - i)S(i,j)=min(h[i],h[j])×(ji),当我们线性减少面积的底时,只考虑高这个因素就可,如果修改最长板,min(h[i],h[j])的值不会改变,修改最长板,可能会增大或减少。

    3.我的代码

    class Solution {
        public int maxArea(int[] height) {
            int low = 0, high = height.length - 1;
            int maxlen = 0;
            int minhigh = 0;
            while (low != high) {
                // calculate current length
                minhigh = height[low];
                if (minhigh > height[high])
                    minhigh = height[high];
                int len = (high - low) * minhigh;
    
                // the max of current length and max length
                if (maxlen < len)
                    maxlen = len;
    
                // compare the length of low and high
                if (height[low] < height[high]) {
                    low++;
                } else
                    high--;
            
            return maxlen;
            
    
        }
    }

     4.金牌思路

    双指针

  • 相关阅读:
    [LeetCode]4Sum
    [LeetCode]3Sum
    [LeetCode]Two Sum
    [LeetCode]Maximal Rectangle
    [LeetCode]Largest Rectangle in Histogram
    [LeetCode]Sudoku Solver
    [LeetCode]Group Anagrams
    jQuery验证控件jquery.validate.js使用说明+中文API
    js操作cookie,实现登录密码保存
    Java中getResourceAsStream的用法
  • 原文地址:https://www.cnblogs.com/xiaoming521/p/14586539.html
Copyright © 2011-2022 走看看