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
  • 相关阅读:
    Asp.Net细节性问题精萃(转)
    开发OFFICE插件总结(转)
    校内网开心网数据同步引发的讨论(转)
    C++指针探讨 (三) 成员函数指针 (转)
    C++指针探讨 (二) 函数指针 (转)
    【原创】编程获取PE文件信息的方法(转)
    为.net开发者提供的一份关于存储过程的评论(转)
    C++指针探讨 (一)数据指针 (转)
    如何批量修改PPT字体、大小、颜色(转)
    搜索引擎里的爱人(转)
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4322150.html
Copyright © 2011-2022 走看看