LeetCode#11. Container With Most Water
来源:互联网 发布:北亚数据恢复中心 编辑:程序博客网 时间:2024/06/06 22:39
题意: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.
题意分析:
这道题目题干已经说的很清楚了,就是找两个点求解最大面积的问题,刚开始的时候,没有考虑到时间复杂度,写了个类似这样的循环
for(int i = 0; i < n-1; i++)
for(int j = i+1; j < n;j++) {
..........
`}
提交后发现超时,仔细分析一下,这个算法是O(n^2),当数据一大的时候,超时便是很自然了。
此时得改进算法,采用两边逼近的方法,因为两边是最宽的,然后逐步往中间逼近,逼近的时候遇见比原来高度低的就跳过,这样可以大大缩短程序运行时间。
一种c++的实现如下:
class Solution {public: int maxArea(vector<int>& height) { int i = 0; int j = height.size()-1; int max_area = 0; int area; while (i < j) { int h = find_min(height[i], height[j]); area = h*(j-i); max_area = find_max(area,max_area); while(height[i] <= h && i < j) i++; while(height[j] <= h && i < j) j--;} return max_area; } int find_min(int a, int b) {if(a >= b) return b;else return a;}int find_max(int a, int b) {if(a >= b) return a;else return b;}};
阅读全文
0 0
- LeetCode 11. Container With Most Water
- [LeetCode]11.Container With Most Water
- LeetCode --- 11. Container With Most Water
- LeetCode 11.Container With Most Water
- [Leetcode] 11. Container With Most Water
- [leetcode] 11.Container With Most Water
- 【leetcode】11. Container With Most Water
- [LeetCode]11. Container With Most Water
- 11. Container With Most Water LeetCode
- leetcode 11. Container With Most Water
- leetcode 11.Container With Most Water
- [LeetCode OJ]11. Container With Most Water
- [leetcode] 11. Container With Most Water
- Leetcode 11. Container With Most Water
- leetcode 11.Container With Most Water
- leetcode 11. Container With Most Water
- LeetCode 11. Container With Most Water
- LeetCode *** 11. Container With Most Water
- 正则实现二代身份证号码验证详解
- 启动hadoop、yarn等服务
- 如何进行通达OA麦枫版软件的授权注册?
- 关于servlet的基础知识
- 通用I/O
- LeetCode#11. Container With Most Water
- 三级缓存
- 关于os.system和os.popen的坑
- jQuery dataTable 个人使用的一点心得
- PHPExcel导出的问题,在PHP7中
- 智能指针学习笔记
- 专家:利用生物钟或治愈癌症 使治疗事半功倍
- mysql数据库用户权限详情
- cap,pcap文件中的ipv4数据包转成ipv6数据包