码迷,mamicode.com
首页 > 其他好文 > 详细

Container with most water

时间:2019-10-16 21:41:10      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:poi   高度   orm   axis   style   turn   water   ble   contain   

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;
    }
}

 

Container with most water

标签:poi   高度   orm   axis   style   turn   water   ble   contain   

原文地址:https://www.cnblogs.com/WakingShaw/p/11688531.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!