標籤:不能 get point article -- pos orm leetcode i++
題目:
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.
題意:
給定n個非負整數a1, a2, ..., an, 每一個代表在座標(i, ai)上的一點,串連(i, ai) and (i, 0)形成n條垂直線。找出兩條垂線,和x座標形成一個容器,使得這個容器包括的水最多。
注意:你不能夠傾斜容器。
演算法分析:
兩邊夾的策略
兩個指標i j往中間走。每次計算i和j之間的面積。假設比眼下最大面積大。則更新最大面積,否則讓兩者之間較小的數的指標往前走。
假設height[i] <= height[j],那麼i++,由於在這裡height[i]是瓶頸,j往裡移僅僅會降低面積,不會再添加area。
這是一個貪心的策略,每次取兩邊圍欄最矮的一個推進,希望擷取很多其它的水。
AC代碼:
public int maxArea(int[] height) { int left=0; int right=height.length-1; int temwater; int res=0; while(left<right) { temwater=Math.min(height[left], height[right])*(right-left); if(temwater>res) res=temwater; if(height[left]<height[right]) left++; else right--; } return res; }
[LeetCode][Java] Container With Most Water