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
  • 相关阅读:
    查找算法——找到序列中第二大的数(修正版)
    排序算法——堆排序
    排序算法——选择排序
    排序算法——冒泡排序
    排序算法——快速排序
    2013年全国各大著名的IT公司薪资待遇大揭密 给出入职场的民工一点建议
    各大IT公司2012校园招聘笔试面试整理
    九大排序算法总结
    mysql之创建数据库,创建数据表
    各种排序算法汇总
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4322150.html
Copyright © 2011-2022 走看看