1. 程式人生 > >LeetCode 11. Container With Most Water (裝最多水的容器)

LeetCode 11. Container With Most Water (裝最多水的容器)

cheng 個數 參考 找到 資料 算法題目 pointer etc html

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.


題目標簽:Array

  這道題目給了我們一個height array, 每一個數字代表一條豎直線的高度,從x軸開始。一開始用暴力法沒通過。所以要用特別方法來做。分析一下,如何才能夠拿到更多的水。如果一根線很低,另外一根很高,那麽水只能裝到低的那根線,等於把高出的區域浪費了。那麽需要找到更高的線來替代低的那條才有希望找到裝水更多的兩條線。設兩個pointer,left 和 right。 從最兩邊開始遍歷,每一次都計算面積,比max大的話就替換。接著把低的那根線的pointer 向另外一邊移動,直到兩個pointers 相遇。

Java Solution:

Runtime beats 31.31%

完成日期:07/11/2017

關鍵詞:Array

關鍵點:Two Pointers

 1 public class Solution 
 2 {
 3     public int maxArea(int[] height) 
 4     {
 5         int left = 0;
 6         int right = height.length-1;
 7         int max_area = -1;
 8         
 9         while(left < right)
10 { 11 int len = right - left; 12 int ht = Math.min(height[left], height[right]); 13 max_area = Math.max(max_area, len*ht); 14 15 if(height[left] < height[right]) 16 left++; 17 else 18 right--; 19 20 } 21 22 return max_area; 23 } 24 }

參考資料:N/A

LeetCode 算法題目列表 - LeetCode Algorithms Questions List

LeetCode 11. Container With Most Water (裝最多水的容器)