1. 程式人生 > 其它 >力扣刷題:11. 盛最多水的容器

力扣刷題:11. 盛最多水的容器

技術標籤:leetcodeleetcode指標演算法c++

題目要求

在這裡插入圖片描述
在這裡插入圖片描述

版本一:憑藉我的直覺但是超時的做法

class Solution {
public:
    int maxArea(vector<int>& height) {
        unsigned MaxArea = 0, beforeHeight = 0, lowerHeight;
        for (unsigned i = 0; i < height.size(); i++)
        {
            if (height.at(i) <= beforeHeight)
{ continue; } beforeHeight = height.at(i); for (unsigned j = i+1; j < height.size(); j++) { lowerHeight = std::min(height.at(i), height.at(j)); MaxArea = std::max(lowerHeight * (j - i), MaxArea)
; } } return MaxArea; } };

整體思路

利用雙層for迴圈,遍歷所有情況,並且在第一層for迴圈中加入判斷條件用於剪枝。找到所有情況中最優的哪一個

版本二: 雙指標方法(官方解法)

class Solution {
public:
    int maxArea(vector<int>& height) {
        unsigned lp = 0, rp = height.size() - 1, maxArea = 0;
        while (lp < rp)
        {
maxArea = std::max(maxArea, std::min(height.at(lp), height.at(rp)) * (rp - lp)); height.at(lp) > height.at(rp) ? --rp : ++lp; } return maxArea; } };

整體思路

一開始先設定兩個指標,一個指向陣列的開頭,一個指向陣列的結尾。初始化當前最大面積為0.

根據當前兩個指標的位置計算得出一個新面積,設定當前最大面積為:
當前最大面積 = max(當前最大面積,新面積)

接著移動兩個指標中取得高度較小的哪一個指標:

  • 如果左邊比右邊高,將右指標往左移一位
  • 如果左邊比右邊低,將左指標往右移一位

再次計算新的面積,改變當前最大面積的值,然後再次移動,直到兩個指標相遇方能結束。

學到了什麼

1、第一次接觸到雙指標方法
2、熟悉了三元表示式的寫法:boolexp?exp1:exp2;

結果

在這裡插入圖片描述