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 }
  • 相关阅读:
    LinkedBlockingQueue
    PriorityBlockingQueue
    js阻止事件冒泡
    java map常用的4种遍历方法
    JAVA jar 和 war 包的区别
    jquery 操作大全
    Java 使用new Thread和线程池的区别
    原生XMLHttpRequest
    socket 和 webscoket 的区别
    GET和POST请求的区别如下
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3373885.html
Copyright © 2011-2022 走看看