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

[leetcode] Container With Most Water

时间:2014-06-27 12:20:47      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:class   blog   code   java   http   tar   

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.

https://oj.leetcode.com/problems/container-with-most-water/

思路1:O(n^2)复杂穷举所有的情况,too young too simple.

思路2::两个指针i,j分别指向首位,选择二者中小的向中间移动,同时更新最大值。这个想法的基础是,如果i的长度小于j,如果移动j,短板在i,不可能找到比当前记录的area更大的值了,只能通过移动i来找到新的可能的更大面积。

public class Solution {
    public int maxArea(int[] height) {
        int n = height.length;
        int maxA = 0;
        int curA = 0;
        int i = 0, j = n - 1;
        while (i < j) {
            if (height[i] <= height[j]) {
                curA = Math.abs(j - i) * height[i];
                if (curA > maxA)
                    maxA = curA;
                i++;
            } else {
                curA = Math.abs(j - i) * height[j];
                if (curA > maxA)
                    maxA = curA;
                j--;
            }
        }

        return maxA;
    }

    public static void main(String[] args) {
        System.out.println(new Solution().maxArea(new int[] { 2, 2, 2 }));
        System.out.println(new Solution().maxArea(new int[] { 1, 2, 3 }));
        System.out.println(new Solution().maxArea(new int[] { 2, 3, 3 }));

    }

}

 

参考:

http://blog.csdn.net/wzy_1988/article/details/17248209

http://www.cnblogs.com/zhaolizhen/p/Containerwater.html

 

 

 

 

[leetcode] Container With Most Water,布布扣,bubuko.com

[leetcode] Container With Most Water

标签:class   blog   code   java   http   tar   

原文地址:http://www.cnblogs.com/jdflyfly/p/3810680.html

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