leetcode解题报告11. Container With Most Water
难度是medium
题目描述
原文:
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.
我的思路
本质上:
输入一个数列,选择两个数字x和y,x和y在数列的位置差是d,假设x和y中较小者是x,那么结果就是x*d。现在问题是在数列中找出两个数x和y,使得结果最大。
基本思路:
暴力遍历两个数即可。但是可以优化提速。分别从数列两端开始遍历,这样两个数字的位置差是最大,现在假设两个数之中x为更小者,那当前最优的结果是x * d,那x端可以继续往内移动。因为d是越来越小的,那么往后即是出现x为更小者,其结果不会超过x * d,所以可以直接跳过。
我的代码
class Solution {
public:
int maxArea(vector<int>& height) {
int ans = 0;
int cur;
int left = 0;
int right = height.size() - 1;
while (right > left) {
if (height[right] > height[left]) {
cur = height[left] * (right - left);
if (ans < cur) {
ans = cur;
}
left++;
} else {
cur = height[right] * (right - left);
if (ans < cur) {
ans = cur;
}
right--;
}
}
return ans;
}
};
阅读官方题解
官方题解
就是我的如上的思路,从数列两端进行遍历。
思想核心总结
理解题目本身的特点。暴力解法一般是思路的入口,但是一般结合题目本身的特点,有对应的提升空间。