记录加入Datawhale第三天,养成每天做题的好习惯
题目描述:
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 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 }