zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    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.

    思路:

    1)两个for循环,遍历所有情况,时间O(n^2). 超时了.

    package area;
    
    public class ContainerWithMostWater {
    
        public int maxArea(int[] height) {
            int n = height.length;
            int maxArea = 0;
            for (int i = 0; i < n - 1; ++i) {
                for (int j = i + 1; j < n; ++i) {
                    int area = Math.min(height[i], height[j]) * (j - i);
                    if (maxArea < area)
                        maxArea = area;
                }
            }
            
            return maxArea;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
        }
    
    }

    2)用两边夹的方式解决。设Aij为坐标(ai, aj)所圈定的区域面积,其中j > i,则Aij = min(ai, aj)*(j - i)。

         如果ai <= aj,则对于i < k < j,有Aik = min(ai, ak) * (k - i)。由于(k - i) < (j - i),min(ai, ak) <= min(ai, aj) ,所以Aik < Aij. 这说明,j没必要往左移,这是只能让i往右移。

         如果ai > aj,则对于i < k < j,有Akj = min(ak, aj) * (j - k)。由于(j - k) < (j - i),min(ak, aj) <= min(ai, aj) ,所以Akj < Aij. 这说明,i没必要往右移,这是只能让j往左移。

    package area;
    
    public class ContainerWithMostWater {
    
        public int maxArea(int[] height) {
            int n = height.length;
            int maxArea = 0;
            int i = 0;
            int j = n - 1;
            while (i < j) {
                int area = Math.min(height[i], height[j]) * (j - i);
                if (height[i] <= height[j]) 
                    ++i;
                else 
                    --j;            
                
                if (area > maxArea)
                    maxArea = area;
            }
            
            return maxArea;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
        }
    
    }
  • 相关阅读:
    还原被删除的对象(域)
    Windows blue系列的安装
    转移active directry数据库文件
    使用指针让两个数交换
    针对被删除的AD DS对象执行授权还原
    这两天的总结
    小小问题
    程序2
    程序4
    程序1
  • 原文地址:https://www.cnblogs.com/null00/p/5047844.html
Copyright © 2011-2022 走看看