[Leetcode] Container With Most Water
阿新 • • 發佈:2018-01-30
當前 represent contains ble max 中間 sent points con
,由點向x軸做垂線,在所有垂線中選出2條,與x軸可以構成一個容器,所有構成的容器中能裝最多多少水。也就是找到一組數據,其“容積”為
Container With Most Water 題解
題目來源:https://leetcode.com/problems/container-with-most-water/description/
Description
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.
Solution
class Solution {
public:
int maxArea(vector<int>& height) {
int res = 0;
int low = 0, high = height.size() - 1;
int tempHeight;
while (low < high) {
tempHeight = min(height[low], height[high]);
res = max(res, (high - low) * tempHeight);
// 要找到low和high之間其它可能的高度,
// 必須高於當前最低高度,才有可能會有更大容積
while (low < high && height[low] <= tempHeight)
low++;
while (low < high && height[high] <= tempHeight)
high--;
}
return res;
}
};
解題描述
這道題題意是,給出一個數組height
,包含n個元素,其中每個數據代表平面直角坐標系上一個點(i, height[i])
res = abs(i - j) + min(height[i], height[j])
最大。
一開始我想到的辦法是2層循環的暴力破解,但是提交上去就一直超時,看了評論區之後發現用從兩邊向中間夾逼的辦法能把時間復雜度從暴力破解的O(n^2)降到O(n)。
[Leetcode] Container With Most Water