Leetcodes Solutions 11 Container With Most Water

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

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.

思路1

以開頭和結尾作為Container的兩端計算水量。然後向中間逼近計算水量。求最大水量。如果中間的高度小於兩邊的,則可以直接跳過

class Solution{public: int maxArea(vector<int>& height){ int water = 0; int i = 0, j = height.size() - 1; while(i < j){ int h = min(height[i], height[j]); water = max(water, (j - i) * h); while(height[i] <= h && i < j)i++; while(height[j] <= h && i < j)j--; } return water; } };

推薦閱讀:

貢獻一個最新版的OpenGrok Docker容器
挑戰真正的編程能力 ——「 PHP挑戰賽 」下周開始
機床為什麼要釋放應力?
面向項目學習編程--之前的廢話
UG編程平面銑最詳細講解,還不快快收藏?

TAG:演算法 | 編程 | 數據結構 |