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

LeetCode--Array--Container With Most Water (Medium)

时间:2019-07-06 00:13:06      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:解法   alt   may   nts   amazon   hat   贪心算法   pre   each   

11. Container With Most Water (Medium)

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.

Note: You may not slant the container and n is at least 2.

Example:

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

技术图片

    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.

solution

第一种解法:暴力解法,也是最容易想到的解法

class Solution {
    public int maxArea(int[] height) {
        int max = 0;
        for (int i = 0; i < height.length; i++)
        {
            for (int j = i + 1; j <height.length; j++)
            {
                int s = 0;
                if (height[i] > height[j])
                    s = height[j] * (j - i);
                else
                    s = height[i] * (j - i);    
                max = s > max ? s : max;   
            }
        }
        return max;
    }
}

第二种解法:贪心算法

public class Solution {
    public int maxArea(int[] height) {
        int maxarea = 0, l = 0, r = height.length - 1;
        while (l < r) 
        {
            maxarea = Math.max(maxarea, Math.min(height[l], height[r]) * (r - l));
            if (height[l] < height[r])
                l++;
            else
                r--;
        }
        return maxarea;
    }
}

reference
https://leetcode.com/articles/container-with-most-water/

总结

第一种暴力算法很容易想到,但时间复杂度为O(n^2);第二种使用的是贪心算法,时间复杂度为O(n)。

Notes
1.可以在暴力算法的基础上得到贪心算法;

LeetCode--Array--Container With Most Water (Medium)

标签:解法   alt   may   nts   amazon   hat   贪心算法   pre   each   

原文地址:https://www.cnblogs.com/victorxiao/p/11141268.html

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