题目来源: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