力扣--盛水最多的容器
生活随笔
收集整理的這篇文章主要介紹了
力扣--盛水最多的容器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
題目:
給你 n 個非負整數 a1,a2,…,an,每個數代表坐標中的一個點 (i, ai) 。在坐標內畫 n 條垂直線,垂直線 i 的兩個端點分別為 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。
說明:
你不能傾斜容器,且 n 的值至少為 2。
下面看下代碼:
#include<iostream> #include<string> #include<vector> #include<map> #include<utility>using namespace std; //盛水最多的容器[雙指針法]class Solution { public:int maxArea(vector<int>& height) {int i = 0;//數組總長int r = height.size() - 1;//存儲水的面積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
思路:兩個指針分別指向數組首尾,求出盛水面積。然后比較兩個指針對應的值大小,值小的先移動。因為算面積以值小的那邊為主,這樣遍歷完找出最大值。
?
參考地址:https://leetcode-cn.com/problems/container-with-most-water/solution/sheng-zui-duo-shui-de-rong-qi-by-leetcode-solution/
總結
以上是生活随笔為你收集整理的力扣--盛水最多的容器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中心扩散算法--最长回文子串
- 下一篇: ubuntu通过pem连接服务器