C++實現(xiàn)LeetCode(11.裝最多水的容器)
[LeetCode] 11. Container With Most Water 裝最多水的容器
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 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 很類似,但又有些不同,那道題讓求整個能收集雨水的量,這道只是讓求最大的一個的裝水量,而且還有一點不同的是,那道題容器邊緣不能算在里面,而這道題卻可以算,相比較來說還是這道題容易一些,這里需要定義i和j兩個指針分別指向數(shù)組的左右兩端,然后兩個指針向中間搜索,每移動一次算一個值和結(jié)果比較取較大的,容器裝水量的算法是找出左右兩個邊緣中較小的那個乘以兩邊緣的距離,代碼如下:
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 中的三元運算符 A?B:C 必須須要有返回值,所以只能用 if..else.. 來替換,不知道 Java 對于三元運算符這么嚴(yán)格的限制的原因是什么。
下面這種方法是對上面的方法進行了小幅度的優(yōu)化,對于相同的高度們直接移動i和j就行了,不再進行計算容量了,參見代碼如下:
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++實現(xiàn)LeetCode(11.裝最多水的容器)的文章就介紹到這了,更多相關(guān)C++實現(xiàn)裝最多水的容器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++賦值函數(shù)+移動賦值函數(shù)+移動構(gòu)造函數(shù)詳解
這篇文章主要介紹了C++賦值函數(shù)+移動賦值函數(shù)+移動構(gòu)造函數(shù)詳解,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08C++編程產(chǎn)生指定范圍內(nèi)的隨機數(shù)
這篇文章主要為大家詳細介紹了C++編程產(chǎn)生指定范圍內(nèi)的隨機數(shù),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-09-09JS調(diào)用C++函數(shù)拋出異常及捕捉異常詳解
這篇文章主要介紹了js調(diào)用C++函數(shù)的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2021-08-08