题目:
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.
解答:
暴力求解,不用说,超时不能AC:
class Solution { public: int area(int i, int j, int ai, int aj) { int length = (i - j > 0) ? (i - j) : (j - i); int width = (ai > aj) ? aj : ai; return (length * width); } int maxArea(vector<int>& height) { int size = height.size(); int ans = -1; for(int i=1; i <= size; i++) { for(int j=1; j <= size; j++) { int tmp = area(i, j, height[i-1], height[j-1]); if(tmp > ans) ans = tmp; } } return ans; } };进一步考虑一下, 是不是 O(N^2) 中每个情况都要考虑并检测,能不能省去?
如果有以下情况:某个container,左侧a处挡板高度为 h_a,右侧b处挡板高度为 h_b(h_a > h_b)。此时,固定b处挡板不动,移动a处挡板到 a~b 区间中任何一处都没有意义。因为:
class Solution { public: int area(int i, int j, int ai, int aj) { int length = (i - j > 0) ? (i - j) : (j - i); int width = (ai > aj) ? aj : ai; return (length * width); } int maxArea(vector<int>& height) { int size = height.size(); int left = 0, right = size - 1; int ans = area(left, right, height[left], height[right]); while(left < right) { if(height[left] < height[right]) left++; else right--; int tmp = area(left, right, height[left], height[right]); ans = (ans > tmp)? ans: tmp; } return ans; } };