• leetcode-11-盛最多水的容器


    问题:

    一、暴力解法:

    package com.example.demo;
    
    public class Test11 {
    
        /**
         * 给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。
         * 在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,
         * 使得它们与 x 轴共同构成的容器可以容纳最多的水。
         *
         * @param height
         * @return
         */
        public int maxArea(int[] height) {
            //暴力解法,双层for
            int maxArea = 0;
            for (int i = 0; i < height.length; i++) {
                for (int j = i + 1; j < height.length; j++) {
                    maxArea = Math.max(maxArea, (j - i) * Math.min(height[i], height[j]));
                }
            }
            return maxArea;
        }
    
        public static void main(String[] args) {
            Test11 t = new Test11();
            int[] arr = {1, 8, 6, 2, 5, 4, 8, 3, 7};
            int i = t.maxArea(arr);
            System.out.println(i);
        }
    }

    二、双支针

    package com.example.demo;
    
    public class Test11 {
    
        /**
         * 给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。
         * 在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,
         * 使得它们与 x 轴共同构成的容器可以容纳最多的水。
         *
         * @param height
         * @return
         */
        public int maxArea(int[] height) {
            //双指针
            int maxArea = 0;
            int left = 0, right = height.length - 1;
            while (left < right) {
                maxArea = Math.max(maxArea, (right - left) * Math.min(height[right], height[left]));
                if (height[right] < height[left]) {
                    right--;
                } else {
                    left++;
                }
            }
    
            return maxArea;
        }
    
        public static void main(String[] args) {
            Test11 t = new Test11();
            int[] arr = {1, 8, 6, 2, 5, 4, 8, 3, 7};
            int i = t.maxArea(arr);
            System.out.println(i);
        }
    }
  • 相关阅读:
    GRIDVIEW鼠标移动行变色
    如何在网页中实现打字效果
    C#的6种常用集合类
    开发和使用Web用户控件
    C# DataGridView的常用用法
    SQL精妙语句
    Web 调试代理软件-Fiddler
    RegisterStartupScript和RegisterClientScriptBlock的用法
    简单地过一下五个控件(ScriptManager、ScriptManagerProxy、UpdatePanel、 UpdateProgress和Timer
    Android4.0 SDK功能详解
  • 原文地址:https://www.cnblogs.com/nxzblogs/p/11224375.html
Copyright © 2020-2023  润新知