本文共 920 字,大约阅读时间需要 3 分钟。
/***********************************************************************************
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. *************************************************************************************/解析:题目意思很简单,就是选择两条线,使其与x轴围成的矩形面积最大。
应该想到用夹逼的方法进行处理。如果左边的数值小于右边,则向右移动,否则向左移动,同时记录最大的面积值。完整AC如下:
class Solution {public: int maxArea(vector & height) { int water = 0; int i = 0, j = height.size() - 1; while (i < j) { int h = min(height[i], height[j]); water = max(water, (j - i) * h); while (height[i] <= h && i < j) i++; //find greater h while (height[j] <= h && i < j) j--; } return water;}};
转载地址:http://bodoi.baihongyu.com/