力扣--盛水最多的容器
生活随笔
收集整理的這篇文章主要介紹了
力扣--盛水最多的容器
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
題目:
給你 n 個(gè)非負(fù)整數(shù) a1,a2,…,an,每個(gè)數(shù)代表坐標(biāo)中的一個(gè)點(diǎn) (i, ai) 。在坐標(biāo)內(nèi)畫 n 條垂直線,垂直線 i 的兩個(gè)端點(diǎn)分別為 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構(gòu)成的容器可以容納最多的水。
說(shuō)明:
你不能傾斜容器,且 n 的值至少為 2。
下面看下代碼:
#include<iostream> #include<string> #include<vector> #include<map> #include<utility>using namespace std; //盛水最多的容器[雙指針?lè)╙class Solution { public:int maxArea(vector<int>& height) {int i = 0;//數(shù)組總長(zhǎng)int r = height.size() - 1;//存儲(chǔ)水的面積int ans = 0;while (i < r) {int area = min(height[i], height[r]) * (r - i);ans = max(ans, area);if (height[i] <= height[r]) {++i;}else {--r;}}return ans;} };int main(){vector<int> vec = {1, 8, 6, 2, 5, 4, 8, 3, 7};Solution so;int num = so.maxArea(vec);cout << num << endl;return 0; }編譯打印:49
思路:兩個(gè)指針?lè)謩e指向數(shù)組首尾,求出盛水面積。然后比較兩個(gè)指針對(duì)應(yīng)的值大小,值小的先移動(dòng)。因?yàn)樗忝娣e以值小的那邊為主,這樣遍歷完找出最大值。
?
參考地址:https://leetcode-cn.com/problems/container-with-most-water/solution/sheng-zui-duo-shui-de-rong-qi-by-leetcode-solution/
總結(jié)
以上是生活随笔為你收集整理的力扣--盛水最多的容器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 中心扩散算法--最长回文子串
- 下一篇: ubuntu通过pem连接服务器