zoukankan      html  css  js  c++  java
  • 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.

    最简单的做法 : 直接遍历。 O(n ^ 2)。

     1 public class Solution {
     2     public int maxArea(int[] height) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         if(height == null || height.length == 0) return 0;
     5         int len = height.length;
     6         int max = Integer.MIN_VALUE;
     7         for(int i = 0; i < len; i ++){
     8             for(int j = i + 1; j < len; j ++){
     9                 int sum = Math.min(height[i],height[j]) * (j - i);
    10                 if(sum > max) max = sum;
    11             }
    12         }
    13         return max;
    14     }
    15 }

    超时。采用双指针来做。

     1 public class Solution {
     2     public int maxArea(int[] height) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         if(height == null || height.length == 0) return 0;
     5         int len = height.length;
     6         int max = Integer.MIN_VALUE;
     7         int i = 0;
     8         int j = len - 1;
     9         while(i < j){
    10             int sum = Math.min(height[i],height[j]) * (j - i);
    11             if(sum > max) max = sum;
    12             if(height[i] < height[j]) i ++;
    13             else j --;
    14         }
    15         return max;
    16     }
    17 }
  • 相关阅读:
    spring源码学习(一) 小小少年
    mysql索引 小小少年
    Java集合框架个人学习笔记 小小少年
    记录一些自己百度到的问题解决方法
    基于内容的医学图像总结
    黑客与画家 第一章
    问题,不是逃避的
    黑客与画家 第二章
    记录最近一周的感受
    暗时间之体会
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3373885.html
Copyright © 2011-2022 走看看