題目來源:https://leetcode.com/problems/container-with-most-water/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.code
Note: You may not slant the container and n is at least 2.orm
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])
,由點向x軸作垂線,在全部垂線中選出2條,與x軸能夠構成一個容器,全部構成的容器中能裝最多多少水。也就是找到一組數據,其「容積」爲ip
res = abs(i - j) + min(height[i], height[j])
最大。leetcode
一開始我想到的辦法是2層循環的暴力破解,可是提交上去就一直超時,看了評論區以後發現用從兩邊向中間夾逼的辦法能把時間複雜度從暴力破解的O(n^2)降到O(n)。get