[leetcode 11] Container With Most Water

记录加入Datawhale第三天,养成每天做题的好习惯

题目描述:

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 and n is at least 2.

 题目要求找到二个柱子之间空间最大,简单点暴力搜索,每二个柱子之间的空间计算一下,时间复杂度较高O(n^2)。这里使用时间复杂度为O(n)的双指针法,从而头向中间遍历。

Java解法:

 1 class Solution {
 2     public int maxArea(int[] height) {
 3     int start = 0;
 4        int end = height.length-1;
 5        int max = 0;
 6        while(start < end){
 7            max = Math.max(max,Math.min(height[start],height[end])*(end - start));
 8            if(height[start] < height[end]){//二者之间的空间打下取决于最矮的那边,所以每次移动矮的那边
 9                start++;
10            }else {
11                end--;
12            }
13        }
14        return max;
15     }
16 }

 

上一篇:用枚举类解决Switch-Case过长的sonar问题Reduce the number of switch cases from 38 to at most 30.


下一篇:ython:运行在Java平台上的python解释器,可以直接把python代码编译成Java字节码执行