题目链接:https://leetcode-cn.com/problems/container-with-most-water/ 面积计算:area = (j-i) * min(height(i), height(j)) 方法一:暴力法,两层循环,时间复杂度O(n^2)
class Solution {
public int maxArea(int[] height) {
int n = height.length;
int maxArea = 0;
int area;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
area = (j - i) * Math.min(height[i], height[j]);
maxArea = Math.max(maxArea, area);
}
}
return maxArea;
}
}
方法二:首尾指针法,时间复杂度O(n)
class Solution {
public int maxArea(int[] height) {
int n = height.length;
int i = 0;
int j = n - 1;
int maxArea = (j - i) * Math.min(height[i], height[j]);
int curArea;
while (i != j) {
if (height[i] < height[j]) {
i++;
} else {
j--;
}
curArea = (j - i) * Math.min(height[i], height[j]);
maxArea = Math.max(maxArea, curArea);
}
return maxArea;
}
}
|