zoukankan      html  css  js  c++  java
  • Container with most water

    Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

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

    这道题其实可以直接用暴力解法求出答案。在高度未知的情况下,暂且可认为宽度越大,面积越大,所以可设左右两个指针,不断缩进,不断求出答案并比较,直到求出最优解

    代码如下:

    class Solution {
        public int maxArea(int[] height) {
            int length = height.length;
            int result = 0;
            int temp = 0;
            for(int i = 0; i < length - 1; i++)
            {
                for(int j = length - 1; j > i; j--)
                {
                    if(height[i] > height[j])
                    {
                        temp = height[j] * (j - i);
                        if(temp > result)
                        {
                            result = temp;
                        }
                    }
                    else
                    {
                        temp = height[i] * (j - i);
                        if(temp > result)
                        {
                            result = temp;
                        }
                    }
                }
            }
            return result;
        }
    }
  • 相关阅读:
    php求2个文件相对路径
    [JZOJ 5818] 做运动
    [JZOJ 5819] 大逃杀
    [JZOJ 5852] 相交
    [JZOJ 5817] 抄代码
    [JZOJ 5791] 阶乘
    [转载](asp.net大型项目实践)
    [转载](你必须知道的.net)
    [转载](闲话WPF)
    .net之 HtmlInputFile
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/11688531.html
Copyright © 2011-2022 走看看