1. 程式人生 > >leetcode11 裝最多水的容器(要學會簡化問題)

leetcode11 裝最多水的容器(要學會簡化問題)

AR nbsp where represent ++ with ner 一個 oge

  • 簡化問題後的代碼
  • /*
        原問題:
        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 n is at least 2.
    
        解析:這是一道考察算法的題目,如果你沒有get到那個點,就會搞得很復雜,但是簡化了問題之後就會恍然大悟,非常的簡單
        簡化的代碼和原來的代碼如下
    
    */class Solution { public: int maxArea(vector<int>& height) { int left = 0; int right = height.size() - 1; int max = 0; while (right > left) { max = std::max(min(height[right], height[left]) * (right - left), max); if (height[right] > height[left]) left
    ++; else right--; } return max; } };

  • 原來自己寫的復雜的代碼
  • struct structure {
        int height;// 表示高度
        int sub;// 表示下標
        structure(int height, int sub):height(height), sub(sub){}
    };
    class Solution {
    public:
        int maxArea(vector<int>& height) {
            
    int max_height = *max_element(height.begin(), height.end()); // left容器存放從左往右遞增的高度,到最高為止 // right容器存放從有往左遞增的高度,到最高為止 vector<structure> left(1, structure(height[0], 0)); vector<structure> right(1, structure(height[height.size() - 1], height.size() - 1)); // 填充left容器 int index = 1; while (true) { if (left[left.size() - 1].height == max_height) break; if (height[index] > left[left.size()-1].height) left.insert(left.end(), structure(height[index], index)); index++; } // 填充right容器 index = height.size() - 2; while (true) { if (right[right.size() - 1].height == max_height) break; if (height[index] > right[right.size() - 1].height) right.insert(right.end(), structure(height[index], index)); index--; } // 不斷將left、right容器的最小的高度pop出來計算該高度水位的面積,找出最大的面積 int max_area = 0; while (left.size() != 1 || right.size() != 1) { if (left[0].height < right[0].height) { int area = left[0].height * (right[0].sub - left[0].sub); if (area > max_area) max_area = area; left.erase(left.begin()); } else { int area = right[0].height * (right[0].sub - left[0].sub); if (area > max_area) max_area = area; right.erase(right.begin()); } } // 單獨處理left、right容器各自剩下的最後一個max_height int area = left[0].height * (right[0].sub - left[0].sub); if (area > max_area) max_area = area; return max_area; } };

  • 1234213412

leetcode11 裝最多水的容器(要學會簡化問題)