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

Leetcode: Container With Most Water

时间:2014-06-10 16:11:31      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

The most strait forward approach is calculating all the possible areas and keep the max one as the result.  This approach needs O(n*n) time complexity, which could not pass OJ (Time limit exceed).

There is so called "closing into the centre" approach.  Idea of which is set two pointer at the start and end of the array (which I has thought about that), then move the shorter pointer each iteration.  The idea be hide this movement is that if we move the longer line, no matter how many steps we move, the new area would be smaller than the one before movement.  This is because area = (end-start)*min(height[start], height[end]) <- after move, (end-start) decrease, min(height[start], height[end]) remains no change, still the "shorter line".

bubuko.com,布布扣
 1 public class Solution {
 2     public int maxArea(int[] height) {
 3         int res = 0;
 4         int begin = 0, end = height.length - 1;
 5         if (height.length == 0 || height.length == 1) return 0;
 6         while (begin < end) {
 7             if (height[begin] < height[end]) {
 8                 if (res < (end - begin) * height[begin]) {
 9                     res = (end - begin) * height[begin];
10                 }
11                 begin++;
12             }
13             else {
14                 if (res < (end - begin) * height[end]) {
15                     res = (end - begin) * height[end];
16                 }
17                 end--;
18             }
19         }
20         return res;
21     }
22 }
bubuko.com,布布扣

 

Leetcode: Container With Most Water,布布扣,bubuko.com

Leetcode: Container With Most Water

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/EdwardLiu/p/3779783.html

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