LeetCode 11. Container With Most Water–Java 解法
此文首發於我的個人博客:LeetCode 11. Container With Most Water–Java 解法–困雨水簡單版 — zhang0peter的個人博客
LeetCode題解文章分類:LeetCode題解
LeetCode 所有題目總結:LeetCode 所有題目總結
題目地址:Container With Most Water - LeetCode
Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
很奇怪這道題目我這麼晚纔看到,之前看到LeetCode 42. Trapping Rain Water
時覺得題目怎麼這麼難,現在才發現,原來這道題目是簡化版的困雨水。
這道題目難度的降低在於柱子是沒有體積的,
暴力破解的自然會超時,如果從2遍向中間夾即可遍歷一遍。
Java解法如下:
class Solution {
public int maxArea(int[] height) {
int maxarea = 0, left = 0, right = height.length - 1;
while (left < right) {
maxarea = Math.max(maxarea, Math.min(height[left], height[right]) * (right - left));
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return maxarea;
}
}
做完這道題目後可以做一下升級難度的題:LeetCode 42. Trapping Rain Water–算法題–c++解法–困雨水複雜版