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.
解题思路:
最直接的尝试是暴搜,o(n2)的时间复杂度,结果TLE。于是不得不寻找更高效的解法。
面积的计算area = min(height[i], height[j]) * |i - j|。可以考虑控制变量,对于i,j之间的line而言,他们的底一定小于|i - j|,那么如果他们的面积要大,就必须有更高的高度。
因此,对于i, j,不妨假设height[i] < height[j],那么如果选取i,而变化j,那么对于height[k] > height[i]的而言,它的高依然是height[i],但是底变小了,所以area不如i,j。对于height[k] < height[i]的,它的area更不可能有更大的出现,于是这种情况下更好的情况必然是不包含i,于是i++。反过来,如果height[i] > height[j],更好的解一定不包含j,于是j--。那么如果height[i] = height[j]呢?更好的情况一定是i和j最后都移动了,此时先移动谁,后移动谁没有关系。
class Solution { public: int maxArea(vector<int> &height) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. /* o(n * n) solution, TLE if(height.size() == 0) return 0; int m = 0; for(int i = 0;i < height.size();i++) { for(int j = i + 1;j < height.size();j++) { int h = min(height[i], height[j]), w = j - i; m = max(m, h * w); } } return m; */ if(height.size() == 0) return 0; int max_area = 0, i = 0, j = height.size() - 1; while(i < j) { max_area = max(max_area, (j - i) * min(height[i], height[j])); if(height[i] < height[j]) i++; else j--; } return max_area; } };