Leetcode 11. Container With Most Water
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,暴力解
过了所有用例但时间太长
int maxArea(int* height, int heightSize) { int max = 0; int temp; for(int i = 0;i < heightSize;i++) { for(int j = i + 1;j <heightSize;j++) { temp = height[i] > height[j]? height[j]:height[i]; temp *= (j - i); if((height[i] == 0) || (height[j] == 0)) temp = 0; max = max > temp?max:temp; } } return max; }
2,提交解
减少运行时间的方法在于减少计算次数,发现题目规律为选取较短的一条边和底的乘积是目标值,这样我们可以通过判断较短边来减少循环次数。
class Solution { public: int maxArea(vector<int>& height) { int length = height.size(); int i = 0; int j = length - 1; int max = 0; int temp; while(i != j) { if(height[i] <= height[j]) { temp = height[i] * (j - i); i++; }else { temp = height[j] * (j - i); j--; } max = max>temp?max:temp; } return max; } };