`
bcyy
  • 浏览: 1809555 次
文章分类
社区版块
存档分类
最新评论

Leetcode Container With Most Water

 
阅读更多

Container With Most Water

Total Accepted:4630Total Submissions:15434My Submissions

Givennnon-negative integersa1,a2, ...,an, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of lineiis 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.


知道原理就是很简单的程序。两边搜索,短板往里走。因为往里走,代表宽度减小,那么宽度小的时候,只有遇上更高的高度才能组成更加大的container。

int maxArea(vector<int> &height) 
    {
	    int area = 0;
	    int i = 0, j = height.size()-1;
	    while (i<j)
	    {
		    area = max(area, (j-i)*min(height[i], height[j]));
		    (height[i] > height[j])? j--:i++;
	    }
	    return area;
    }


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics