每每看及官方解法,总羞愧难当,官方解法简洁易懂,何时才能达到这种水平呢?只有不断努力了。
package leetCode;
//官方解法
class Solution {
public int maxArea(int[] height) {
int maxarea = 0, l = 0, r = height.length - 1;
while (l < r) {
maxarea = Math.max(maxarea, Math.min(height[l], height[r]) * (r - l));
if (height[l] < height[r])
l++;
else
r--;
}
return maxarea;
}
}
//我的思路:每次比较单侧,利用偏移量来比较,和官方解法对比后,感觉我的思路就是暴力法
public class BestWaterContainer {
public static void main(String[] args) {
//int[] heights= {10,9,8,7,6,5,4,3,2,1};//25
//int[] heights= {1,8,6,2,5,4,8,3,7};//49
//int[] heights= {1,1};
//int[] heights= {1,2,1};
int[] heights= {
2,3,10,5,7,8,9};//36
System.out.println(maxArea(heights));
}
public static int maxArea(int[] heights) {
//初始化最大值
int max = getAcreage(0, heights.length-1, heights);
System.out.println("初始化的Max:"+ max);
int i = 0;
int j = heights.length - 1;
int offsetLeft = 1;
int offsetRight = 1;
while ((i+offsetLeft)<=(j+offsetRight)&&(i+offsetLeft)<heights.length||(j-offsetRight)>= 0) {
// 首先是0和lenght-1,然后让其分别与单侧相邻点比较,取大者,计算值,若值更大者留下
if ((i+offsetLeft)<heights.length&&heights[i]< heights[i + offsetLeft]) {
int area = getAcreage(i + offsetLeft, j, heights);
if (area > max) {
max = area;
i = i + offsetLeft;
}
//System.out.println("循环中的max:i :"+max);
}
if ((j-offsetRight)>= 0&&heights[j] < heights[j - offsetRight]) {
int area = getAcreage(i, j-offsetRight, heights);
if (area > max) {
max = area;
j = j - offsetRight;
}
//System.out.println("循环中的max:j :"+max);
}
offsetLeft++;
offsetRight++;
}
return max;
}
public static int getAcreage(int startPoint, int endPoint, int heights[]) {
int height = Math.min(heights[startPoint], heights[endPoint]);
int wide = endPoint - startPoint;
return wide * height;
}
}