11. Container With Most Water
2018-03-13 08:57
399 查看
问题描述
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.
题目链接:
思路分析
给一个高度的数组,使得形成的容器的容积最大。容积 = min(height) * abs(i - j)。正常的暴力破解O(n)会TLE,所以我们假定一开始相距最远的两根形成的container的容积是最大的,而指针移动的条件则是不断的去寻找更高的height,因为更高的height才能保证弥补i和j之间的差距,逐步向中间靠近。
代码
class Solution { public: int maxArea(vector<int>& height) { int maxArea = 0, low = 0, high = height.size() - 1; while (low < high){ maxArea = max(maxArea, min(height[low], height[high])*(high - low)); if (height[low] < height[high]) low++; else high--; } return maxArea; } };
时间复杂度:O(n)
空间复杂度:O(1)
反思
很巧妙的方法,也不像动态规划,但是非常有效。相关文章推荐
- LeetCode 11 - Container With Most Water
- leetcode 11 -- Container With Most Water
- 11. Container With Most Water
- Leet Code 11 Container With Most Water - Java
- 11. Container With Most Water
- 11. Container With Most Water
- Leetcode 11 Container With Most Water
- 【leetcode】【11】Container With Most Water
- 11.Container With Most Water
- 11. Container With Most Water
- [Leetcode 43] 11 Container With Most Water
- [11]Container With Most Water
- 11. Container With Most Water
- 第三周:11. Container With Most Water
- leetcode 11 Container with Most Water
- 11. Container With Most Water
- LeetCodeOJ_11_m_Container With Most Water
- leetcode 11:Container With Most Water
- [leetcode-11]container with most water(C)
- Middle-题目31:11. Container With Most Water