zoukankan      html  css  js  c++  java
  • Container With Most Water

    Container With Most Water

    问题:

    Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

    思路:

      双指针,减少短板

    我的代码:

    public class Solution {
        public int maxArea(int[] height) {
            if(height == null || height.length <= 1)    return 0;
            int left = 0;
            int right = height.length - 1;
            int maxArea = Math.min(height[left],height[right])*(right - left);
            while(left < right)
            {
                int curLeft = left;
                int curRight = right;
                if(height[left] < height[right])
                {
                    while(left < right && height[left] <= height[curLeft])
                    {
                        left++;
                    }
                    maxArea = Math.max(Math.min(height[left],height[right])*(right - left), maxArea);
                }
                else
                {
                    while(left < right && height[right] <= height[curRight])
                    {
                        right--;
                    }
                    maxArea = Math.max(Math.min(height[left],height[right])*(right - left), maxArea);
                }
            }
            return maxArea;
        }
    }
    View Code

    他人代码:

    public class Solution {
        public int maxArea(int[] height) {
            if (height == null) {
                return 0;
            }
            
            int left = 0;
            int right = height.length - 1;
            int maxArea = 0;
            
            while (left < right) {
                int h = Math.min(height[left], height[right]);
                int area = h * (right - left);
                maxArea = Math.max(maxArea, area);
                
                if (height[left] < height[right]) {
                    // 如果左边界比较低,尝试向右寻找更高的边界
                    left++;
                } else {
                    // 如果右边界比较低,尝试向左寻找更高的边界
                    right--;
                }
            }
            
            return maxArea;
        }
    }
    View Code

    学习之处:

    • 思路一致,他人的代码更加简洁清楚,我的代码虽然循环多,但是时间复杂度是一致的,都是O(n),另外我的代码里面少计算了好多次maxArea
  • 相关阅读:
    个人:我的2011生活看板
    个人管理:公司做的稻盛阿米巴培训笔记
    使用TOGAF来做业务架构 价值驱动产品开发
    30天敏捷结果(21)正面失败,吸取教训,改善结果
    2010年12月blog汇总:敏捷个人
    30天敏捷结果(25):固定时间,灵活范围
    101与金根回顾敏捷个人:(11)执行力
    团队管理:设计团队的一周
    云:构建云计算的核心技术与平台
    读书笔记:千万别学英语
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4322150.html
Copyright © 2011-2022 走看看