首页 > 代码库 > [leetcode] Container With Most Water
[leetcode] 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.
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。