[LeetCode][Java] Container With Most Water

來源:互聯網
上載者:User

標籤:不能   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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.