题目如下:
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.
翻译略去,直接说思路,刚开始我想错了,直接想成了计算题型面积(a[j]-a[i])*(j-i)/2,而且还用了个穷举法。
这里应该计算并比较min(h[i], h[j]) * (j - i)。
选择从两端到中间递归查找,程序如下:
class Solution { public: int maxArea(vector<int> &height) { int ret = findMax(height, 0, height.size()-1, 0); return ret; } int findMax(vector<int> &h, int i , int j , int area) { int temp = 0; if(i == j) { cout << i << " " << j << endl; return area; } temp = (h[i]>h[j]?h[j]:h[i]) * (j - i) ; if(h[i] > h[j]) { j -= 1; } else { i += 1; } if(temp < area) findMax(h, i, j , area); else findMax(h, i, j, temp); } };
非递归版本:
class Solution { public: int maxArea(vector<int> &height) { int area = 0; int iStart = 0; int iEnd = height.size()-1; vector<int> h = height; while(iStart != iEnd) { int temp = (h[iStart] > h[iEnd]?h[iEnd]:h[iStart]) * (iEnd - iStart); if(temp > area) { area = temp; } if(h[iStart] > h[iEnd]) { iEnd -= 1; } else { iStart += 1; } } return area; } };
加油!
时间: 2024-10-07 15:04:50