LeetCodeContainer With Most Water 解題報告

來源:互聯網
上載者:User

【題目】

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. 【解析】

題意:在二維座標系中,(i, ai) 表示 從 (i, 0) 到 (i, ai) 的一條線段,任意兩條這樣的線段和 x 軸組成一個木桶,找出能夠盛水最多的木桶,返回其容積。

兩層 for 迴圈的暴力法會逾時,所以儘早放棄這種懶惰的想法。

有沒有 O(n) 的解法。

答案是有,用兩個指標從兩端開始向中間靠攏,如果左端線段短於右端,那麼左端右移,反之右端左移,知道左右兩端移到中間重合,記錄這個過程中每一次組成木桶的容積,返回其中最大的。(想想這樣為何合理。)

public class Solution {    public int maxArea(int[] height) {        if (height.length < 2) return 0;        int ans = 0;        int l = 0;        int r = height.length - 1;        while (l < r) {            int v = (r - l) * Math.min(height[l], height[r]);            if (v > ans) ans = v;            if (height[l] < height[r]) l++;            else r--;        }        return ans;    }}

合理性解釋:當左端線段L小於右端線段R時,我們把L右移,這時捨棄的是L與右端其他線段(R-1, R-2, ...)組成的木桶,這些木桶是沒必要判斷的,因為這些木桶的容積肯定都沒有L和R組成的木桶容積大。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.