zoukankan      html  css  js  c++  java
  • LeetCode#11-盛最多水的容器

    package shuangzhizhen;
    /*
    11. 盛最多水的容器
    给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
    
    说明:你不能倾斜容器,且 n 的值至少为 2。
    示例:
    
    输入:[1,8,6,2,5,4,8,3,7]
    输出:49
    
        解题思路:双指针
     */
    public class p11 {
        public static int maxArea(int[] height) {
            int left=0,right=height.length-1;
            int max=(right-left)*Math.min(height[left],height[right]);
            while (left<right){
                if(height[left]<height[right]){
                    left++;
                    max=Math.max(max,(right-left)*Math.min(height[left],height[right]));
                }
                else {
                    right--;
                    max=Math.max(max,(right-left)*Math.min(height[left],height[right]));
                }
            }
            return max;
    
        }
    
        public static void main(String[] args) {
            int nums[]={1,8,6,2,5,4,8,3,7};
            System.out.println(maxArea(nums));
        }
    }
    

      运行结果:

  • 相关阅读:
    socket架构
    异常处理
    类的装饰器
    with&as上下文管理协议
    软件开发规范
    面向对象-描述符
    面向对象-迭代器
    面向对象编程多种特性
    体验Visual Studio 2015 之 MVC
    MVC 好记星不如烂笔头之 ---> 全局异常捕获以及ACTION捕获
  • 原文地址:https://www.cnblogs.com/jifeng0902/p/13269404.html
Copyright © 2011-2022 走看看