Leetcode——11. Container With Most Water
LeetCode with 11 container most Water
2023-09-11 14:22:29 时间
1. 概述
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轴。在这样的情况下求取两个元素组成的长方形面积最大。解题思路
(1)暴力搜索
也就是每种情况都去遍历一遍,肯定能找到一个最优解,但是这样的方式很暴力(O(N^2)),直接导致gg
显然这样的方式是不能使用的。
(2)面积最大时条件
通过分析面积最大时的条件,可以知道寻找到的两个数应该尽量的大,而且他们的距离应该尽量大。因而在搜索的策略上就选择:从数组的前端和末尾开始搜索;在每次搜索的过程中记录面积最大值,两边沿着数组元素大的方向搜索。原理就如下图所示
2. 编码
class Solution {
public:
int maxArea(vector<int>& height)
{
int len(height.size()); //容器的大小
int high(0); //得到的长方体的高度
if(1==len || 0==len) return 0;
if(2 == len)
{
high = min(height[0], height[1]);
return high;
}
int area(0); //最大的面积
//方法2,O(N)
int left(0), right(len-1);
while(left < right)
{
area = max(area, min(height[left], height[right])*(right-left));
if(height[left] < height[right])
++left;
else
--right;
}
return area;
}
};
性能
相关文章
- Leetcode: Word Squares && Summary: Another Important Implementation of Trie(Retrieve all the words with a given Prefix)
- Leetcode: Valid Word Abbreviation
- Leetcode: Longest Substring with At Most K Distinct Characters && Summary: Window做法两种思路总结
- Leetcode: Best Time to Buy and Sell Stock with Cooldown
- Leetcode: Largest Rectangle in Histogram
- leetcode Container With Most Water
- 【LeetCode】11. Container With Most Water
- 【LeetCode】30. Substring with Concatenation of All Words
- [leetcode]Permutation Sequence
- 【leetcode】111:二叉树的最小深度
- [LeetCode] 1330. Reverse Subarray To Maximize Array Value 翻转子数组得到最大的数组值
- [LeetCode] 1325. Delete Leaves With a Given Value 删除给定值的叶子结点
- [LeetCode] 1277. Count Square Submatrices with All Ones 统计全为 1 的正方形子矩阵
- [LeetCode] 1240. Tiling a Rectangle with the Fewest Squares 铺瓷砖
- [LeetCode] 1186. Maximum Subarray Sum with One Deletion 删除一次得到子数组最大和
- [LeetCode] 1010. Pairs of Songs With Total Durations Divisible by 60 总持续时间可被60整除的歌曲
- [LeetCode] 982. Triples with Bitwise AND Equal To Zero 按位与为零的三元组
- [LeetCode] 928. Minimize Malware Spread II 最大程度上减少恶意软件的传播之二
- [LeetCode] 924. Minimize Malware Spread 最大程度上减少恶意软件的传播
- [LeetCode] 472. Concatenated Words 连接的单词
- [LeetCode] 471. Encode String with Shortest Length 最短长度编码字符串
- [LeetCode] 363. Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K
- [LeetCode] 340. Longest Substring with At Most K Distinct Characters 最多有K个不同字符的最长子串
- [LeetCode] 6. ZigZag Conversion 之字型转换字符串
- Leetcode——17. Letter Combinations of a Phone Number