11. Container With Most Water
1.小白解法
class Solution { public: int maxArea(vector<int> &height) { auto left = height.begin(); auto right = height.end() - 1; int sum = 0; while (left != right) { if (*left <= *right) { int tmpsum = *left * (right - left); if (tmpsum > sum) { sum = tmpsum; } left++; } if (*left > *right) { int tmpsum = *right * (right - left); if (tmpsum > sum) { sum = tmpsum; } right--; } } return sum; } };
很暴力的解法,将所有结果算出,找到最大的结果。
简化版本
class Solution { public: int maxArea(vector<int> &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++; while (height[j] <= h && i < j) j--; } return water; } };
网上解法把我最初的想法简化了一下。
感悟
自己通关