欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++實(shí)現(xiàn)LeetCode(11.裝最多水的容器)

 更新時(shí)間:2021年07月12日 11:11:49   作者:Grandyang  
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(11.裝最多水的容器),本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

[LeetCode] 11. Container With Most Water 裝最多水的容器

Given n non-negative integers a1a2, ..., an , where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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 nis at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

這道求裝最多水的容器的題和那道 Trapping Rain Water 很類(lèi)似,但又有些不同,那道題讓求整個(gè)能收集雨水的量,這道只是讓求最大的一個(gè)的裝水量,而且還有一點(diǎn)不同的是,那道題容器邊緣不能算在里面,而這道題卻可以算,相比較來(lái)說(shuō)還是這道題容易一些,這里需要定義i和j兩個(gè)指針?lè)謩e指向數(shù)組的左右兩端,然后兩個(gè)指針向中間搜索,每移動(dòng)一次算一個(gè)值和結(jié)果比較取較大的,容器裝水量的算法是找出左右兩個(gè)邊緣中較小的那個(gè)乘以?xún)蛇吘壍木嚯x,代碼如下:

C++ 解法一:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int res = 0, i = 0, j = height.size() - 1;
        while (i < j) {
            res = max(res, min(height[i], height[j]) * (j - i));
            height[i] < height[j] ? ++i : --j;
        }
        return res;
    }
};

Java 解法一:

public class Solution {
    public int maxArea(int[] height) {
        int res = 0, i = 0, j = height.length - 1;
        while (i < j) {
            res = Math.max(res, Math.min(height[i], height[j]) * (j - i));
            if (height[i] < height[j]) ++i;
            else --j;
        }
        return res;
    }
}

這里需要注意的是,由于 Java 中的三元運(yùn)算符 A?B:C 必須須要有返回值,所以只能用 if..else.. 來(lái)替換,不知道 Java 對(duì)于三元運(yùn)算符這么嚴(yán)格的限制的原因是什么。

下面這種方法是對(duì)上面的方法進(jìn)行了小幅度的優(yōu)化,對(duì)于相同的高度們直接移動(dòng)i和j就行了,不再進(jìn)行計(jì)算容量了,參見(jiàn)代碼如下:

C++ 解法二:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int res = 0, i = 0, j = height.size() - 1;
        while (i < j) {
            int h = min(height[i], height[j]);
            res = max(res, h * (j - i));
            while (i < j && h == height[i]) ++i;
            while (i < j && h == height[j]) --j;
        }
        return res;
    }
};

Java 解法二:

public class Solution {
    public int maxArea(int[] height) {
        int res = 0, i = 0, j = height.length - 1;
        while (i < j) {
            int h = Math.min(height[i], height[j]);
            res = Math.max(res, h * (j - i));
            while (i < j && h == height[i]) ++i;
            while (i < j && h == height[j]) --j;
        }
        return res;
    }
}

到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(11.裝最多水的容器)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)裝最多水的容器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論