バックルLeetcode 11.水分が最も多い容器

水が最も多いコンテナ

もしnは非負整数A 1、A 2、...、A nは、点(それぞれの座標の数を表し、IAIを)。座標にn本の垂直線を描画します垂直線iの2つの端点は(iai)と(i、0)です。2本の線を見つけて、x軸で形成されるコンテナが最も多くの水を保持できるようにします。

注:コンテナーを傾けることはできずnの値は2以上です。

img

図の縦線は、入力配列[1,8,6,2,5,4,8,3,7]を表しています。この場合、コンテナが水を保持できる最大値(青色の部分で表される)は49です。

例:

输入:[1,8,6,2,5,4,8,3,7]
输出:49

解決策

暴力法(タイムアウト)

明らかに、直接的な暴力はタイムアウトし、コードを見ればそれを理解できます

int maxArea(vector<int>& height) {
        int max = 0;
        int L = height.size();
        for (int i = 0; i < L-1; i++){
            for (int j = 1; j < L; j++){
                int temp = min(height[i], height[j]) * (j-i);
                if(temp > max) max = temp;
        }
    }
    return max;
}

ダブルポインター方式

短いボードの効果に従って、頭と尾にポインターを設定します。最大音量は、両側の最も短いボードによって決定される必要があるため、ポインターが合うまで、短いボードを中央に移動させます

int maxArea(vector<int> &height)
    {
        int result = 0;
        int heightSize = int(height.size());
        int leftIndex = 0;
        int rightIndex = heightSize - 1;

        while (leftIndex != rightIndex)
        {
            int tmpHeight;
            int tmpWidth = rightIndex - leftIndex;
            //短的一侧向中间移动
            if (height[leftIndex] < height[rightIndex])
            {
                tmpHeight = height[leftIndex];
                leftIndex++;
            }
            else
            {
                tmpHeight = height[rightIndex];
                rightIndex--;
            }
            int tmpResult = tmpWidth * tmpHeight;
            if (tmpResult > result)
            {
                result = tmpResult;
            }
        }
        return result;
}

おすすめ

転載: www.cnblogs.com/coderzjz/p/12727652.html