【每天一道編程系列-2018.2.28】(Ans)

【題目描述】


  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. 



【題目大意】


  找兩條豎線然後這兩條線以及X軸構成的容器能容納最多的水。 


【解題思路】



  使用貪心算法 
  1.首先假設我們找到能取最大容積的縱線爲 i, j (假定i < j),那麼得到的最大容積 C = min( ai , aj ) * ( j- i) ; 
  2.下面我們看這麼一條性質: 
  ①: 在 j 的右端沒有一條線會比它高!假設存在 k |( j < k && ak > aj) ,那麼 由 ak > aj,所以 min(ai, aj, ak) =min(ai, aj) ,所以由i, k構成的容器的容積C’ = min(ai, aj) * (k - i) > C,與C是最值矛盾,所以得證j的後邊不會有比它還高的線; 
  ②:同理,在i的左邊也不會有比它高的線;這說明什麼呢?如果我們目前得到的候選: 設爲 x, y兩條線(x< y),那麼能夠得到比它更大容積的新的兩條邊必然在[x, y]區間內並且 ax’ >= ax , ay’ >= ay; 
   3.所以我們從兩頭向中間靠攏,同時更新候選值;在收縮區間的時候優先從x, y中較小的邊開始收縮; 



【本題答案】


package blog;

/**
 * @author yesr
 * @create 2018-02-28 下午11:18
 * @desc
 **/
public class Test0228 {

    public int maxArea(int[] height) {

        // 參數校驗
        if (height == null || height.length < 2) {
            return 0;
        }


        // 記錄最大的結果
        int result = 0;

        // 左邊的豎線
        int left = 0;
        // 右邊的豎線
        int right = height.length - 1;

        while (left < right) {
            // 設算當前的最大值
            result = Math.max(result, Math.min(height[left], height[right]) * (right - left));
            // 如果右邊線高
            if (height[left] < height[right]) {
                int k = left;
                // 從[left, right - 1]中,從左向右找,找第一個高度比height[left]高的位置
                while (k < right && height[k] <= height[left]) {
                    k++;
                }

                // 從[left, right - 1]中,記錄第一個比原來height[left]高的位置
                left = k;
            }
            // 左邊的線高
            else {
                int k = right;
                // 從[left + 1, right]中,從右向左找,找第一個高度比height[right]高的位置
                while (k > left && height[k] <= height[right]) {
                    k--;
                }

                // 從[left, right - 1]中,記錄第一個比原來height[right]高的位置
                right = k;
            }
        }

        return result;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章