iT邦幫忙

2025 iThome 鐵人賽

0

題目說明

  1. Container With Most Water
    給你一個整數陣列 height,每個元素代表垂直線的高度。
    找出 兩條線與 x 軸形成的容器能盛最多的水,返回容器面積最大值。
    • 面積公式:area = min(height[i], height[j]) * (j - i)

範例

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
解釋:用第 2 根和第 9 根線形成的容器面積最大:min(8,7)*(8-1)=49

Input: height = [1,1]
Output: 1

Python 解法(雙指針)

def maxArea(height):
left, right = 0, len(height) - 1
max_area = 0
while left < right:
max_area = max(max_area, min(height[left], height[right]) * (right - left))
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_area

Java 解法(雙指針)

class Solution {
public int maxArea(int[] height) {
int left = 0, right = height.length - 1, maxArea = 0;
while (left < right) {
int area = Math.min(height[left], height[right]) * (right - left);
maxArea = Math.max(maxArea, area);
if (height[left] < height[right]) left++;
else right--;
}
return maxArea;
}
}

Java vs Python 差異
• Python 用內建 max() 和 min(),語法簡潔
• Java 用 Math.max() 和 Math.min()
• 核心邏輯都是 雙指針從兩端向中間移動,每次選擇較小邊向內縮,以嘗試最大面積

複雜度分析
• 時間複雜度:O(n),左右指針每個位置最多走一次
• 空間複雜度:O(1),只使用常數變數


上一篇
day 29 Subarray Sum Equals K
系列文
不熟程式的我在leetcode打滾30天30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言