LeetCode刷题(C++)——Container With Most Water
来源:互联网 发布:小米笔记本 游戏 知乎 编辑:程序博客网 时间:2024/06/14 05:31
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,3,2,5,6],在坐标系上显示如下,目的是要寻找两条垂直线与x轴组成的容器之间的最大面积,感觉类似于木桶效应。下图中最大的面积是3和6之间组成的区域。
解法1:暴力解法,时间复杂度为O(n^2),通不过,稍微改进一下也是能够通过的。
class Solution {public: int maxArea(vector<int>& height) { if (height.size() < 2)return 0;int maxarea = 0;for (int i = 0; i < height.size();++i){if (height[i] != 0){for (int j = i + (maxarea / height[i]);j < height.size();++j) //如果是直接暴力解法 j=i+1;会超时{int len = j - i;int wid = (height[i] > height[j]) ? height[j] : height[i];int area = len*wid;if (area > maxarea)maxarea = area;}}}return maxarea; }};
解法2: 时间复杂度为O(n)
设置两个指针i和j,分别指向数组的两头,当a[i]>a[j]时,j往前移动,否则i往后移动,同时之前最大的面积比较。
class Solution {public: int maxArea(vector<int>& height) { if (height.size() < 2)return 0;int maxarea = 0;int i = 0, j = height.size() - 1;while (i < j){maxarea = max(maxarea, min(height[i], height[j])*(j - i));if (height[i] < height[j])++i;else--j;}return maxarea; }};
1 0
- LeetCode刷题(C++)——Container With Most Water
- LeetCode 之 Container With Most Water — C 实现
- LeetCode——Container With Most Water
- leetcode——Container With Most Water
- Container With Most Water——LeetCode
- leetcode——Container With Most Water
- LeetCode——Container With Most Water
- Container With Most Water —— Leetcode
- leetcode——Container With Most Water
- LeetCode——Container With Most Water
- LeetCode——Container With Most Water
- leetcode—Container With Most Water
- 【leetcode】Array——Container With Most Water(11)
- LeetCode(11)——Container With Most Water
- 刷LeetCode(11)——Container With Most Water
- [C++]LeetCode: 39 Container With Most Water
- [leetcode-11]container with most water(C)
- Leetcode c语言-Container With Most Water
- 死变态的跳台阶
- Linux常用命令
- redis的数据类型和指令
- BRO的local.bro 文件 /usr/local/bro/share/bro/site
- Oracle优化:避免全表扫描
- LeetCode刷题(C++)——Container With Most Water
- CentOS7搭建SAMBA服务器实现与WIN10匿名共享文件
- 命令、语句疑难及相关理解
- CentOS下torque集群配置(三)配置NIS统一管理所有linux账户和密码
- Android短信监听实现,及Android4.4之后短信机制变更
- python基础-动态加载lazy_import(利用__import__)
- 响应式网页设计
- iOS开发 非常全的三方库、插件、大牛博客等等
- C# 入门(15) LINQ(Language Integrated Query)