classSolution { public: intmaxArea(vector<int>& height){ int max = 0, n = height.size(); for (int first = 0; first < n; first++) { if (height[first] == 0) { continue; } for (int second = first + max/height[first] + 1; second < n; second++) { int s = min(height[first], height[second]) * (second - first); if (s > max) { max = s; } } } return max; } };
性能:340 ms 9.8 MB
双指针法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: inlineintMax(constint& a, constint& b){ return a>b?a:b; } inlineintMin(constint& a, constint& b){ return a<b?a:b; } intmaxArea(vector<int>& height){ registerint result = 0; registerint former = 0, later = height.size() - 1; while (former < later) { result = Max(result, Min(height[former], height[later]) * (later - former)); height[former]<height[later]?former++:later--; }