[leetcode]Container With Most Water

新博文地址:[leetcode]Container With Most Water

http://oj.leetcode.com/problems/container-with-most-water/

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.

 第一反应肯定是暴力,时间复杂度为n^2,毫无意外的超时了,leetcode的case  的“ 长度”还是蛮变态的。双指针在leetcode中的应用还是蛮多的。

public int maxArea(int[] height) {
		int left = 0;
		int right = height.length - 1;
		int max = 0;
		while(left < right){
			int high = height[left] > height[right] ? height[right] : height[left];
			int area = (right - left) * high;
			if(area > max){
				max = area;
			}//短板效应,只有挪动短板才可能“增大”面积
			if(height[right]> height[left]){
				left++;
			}else{
				right--;
			}
		}
		return max;
	}

 

你可能感兴趣的:(LeetCode)