Leetcode 11. Container With Most Water

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Container With Most Water

2. Solution

  • Brute Force
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int maxArea(vector<int>& height) {
int length = height.size();
int maxArea = 0;
int area = 0;
for(int i = 0; i < length; i++) {
for(int j = i + 1; j < length; j++) {
area = (j - i) * (height[i]<height[j]?height[i]:height[j]);
if(maxArea < area) {
maxArea = area;
}
}
}
return maxArea;
}
};
  • Two Pointer Approach
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    class Solution {
    public:
    int maxArea(vector<int>& height) {
    int i = 0;
    int j = height.size() - 1;
    int maxArea = 0;
    int area = 0;
    while(i < j) {
    area = (j - i) * (height[i]<height[j]?height[i]:height[j]);
    if(maxArea < area) {
    maxArea = area;
    }
    height[i]<height[j]?i++:j--;
    }
    return maxArea;
    }
    };

参考资料

  1. https://leetcode.com/problems/container-with-most-water/description/
如果有收获,可以请我喝杯咖啡!