zoukankan      html  css  js  c++  java
  • LeetCode 11. Container With Most Water

    原题链接在这里:https://leetcode.com/problems/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.

    The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

    Example:

    Input: [1,8,6,2,5,4,8,3,7]
    Output: 49

    题解:

    双指针夹比,更新最大面积,每次移动小的那个夹板,因为储水量是由短的夹板决定的,移动大的夹板不会使面积更大.

    Time Complexity: O(n). Space: O(1).

    AC Java:

     1 public class Solution {
     2     public int maxArea(int[] height) {
     3         if(height == null || height.length == 0){
     4             return 0;
     5         }
     6         int res = 0;
     7         int l = 0;
     8         int r = height.length-1;
     9         while(l<r){
    10             //r-l是底长, 取左右两侧高度较小者为高
    11             res = Math.max(res, (r-l) * Math.min(height[l], height[r]));
    12             //移动短的边
    13             if(height[l] < height[r]){
    14                 l++;
    15             }else{
    16                 r--;
    17             }
    18         }
    19         return res;
    20     }
    21 }

    类似Trapping Rain Water.

  • 相关阅读:
    VMware Workstation安装CentOs7固定ip地址
    使用阿里云oss
    使用Yapi展示你的api接口
    .net core使用MQTT
    CentOS 7服务器安装brook和bbr加速
    博客主题
    自定义控件
    winform数据绑定
    is as 运算符
    反射
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4839890.html
Copyright © 2011-2022 走看看