Container With Most Water -- leetcode

原題


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.數組

翻譯

給你一串數字a1,a2,a3...,每一個數字表明座標系上一個點,如a3 = 4的話就是表明(3,4)這個點.從這些全部的點中找出兩個點,這兩個點知足: 以這兩個點往x軸作垂線,與x軸造成的水桶能夠盛下作多的水,即面積最大.
如 (1, 2, 5) 面積爲: 2; (3, 2, 4) 面積爲 6翻譯

解題思路

  • 定義一個頭指針(lo)指向開始,再定義一個尾指針(hi)指向數組的末尾.指針

  • 初始的面積是最外面兩條邊最小的乘他們的距離(hi-lo)*Math.min(height[hi],height[lo]);code

  • 以後兩個指針開始向中間移動,先計算此時的面積,若是比以前的大,面積更新爲如今的面積,以後哪個小就往中間移動哪個.直到兩個相碰,中止循環.orm


代碼 (JavaScript)

/**
 * @param {number[]} height
 * @return {number}
 */

var maxArea = function(height) {
    let len = height.length;
    
    if (len < 2)
        return 0;
    
    let res = 0,       
        lo   = 0,         /* first pointer */
        hi   = len - 1;  /* last pointer  */
    
    while (lo < hi) {
        let area = (hi - lo) * Math.min(height[hi], height[lo]);
        res = Math.max(res, area);
        
        if (height[lo] < height[hi]) {
            lo++;
        } else {
            hi--;
        }   
    }
    
    return res;
};
相關文章
相關標籤/搜索