【一天一道LeetCode】#11Container With Most Water
2016-04-06 23:24
826 查看
一天一道LeetCode系列
(一)题目
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.
(二)解题
题意:给定一组高度值,选取其中两个使得两者构成的容器的容量最大。按照题意,一个双重循环可以很简单的解决问题,可是复杂度太高了,O(n^2)。
那么我们可以寻找O(n)的解法。
其实也比较简单,定义两个指针,分别指向头和尾,由于容易装水的容量是由小端决定,所以指针移动的准则就是小端指针移动。
只需要遍历一遍就能得到最大值。
class Solution { public: int maxArea(vector<int>& height) { int i = 0; int j = height.size()-1; int max=0; while(j>i) { int con = 0; int min = height[i]>height[j]?height[j]:height[i]; if(j==i+1){con = min;} else con = min *(j-i); if(height[i]>height[j]) { j--; } else i++; if(con>max) max=con; } return max; } };
相关文章推荐
- 训练集(train set) 验证集(validation set) 测试集(test set)
- Count ways to reach the n’th stair
- Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-2.xml, reason: Connect
- leetcode——70——Climbing Stairs
- 最简实例说明WAIT、NOTIFY、NOTIFYALL的使用方法
- HDOJ 1789-Doing Homework again【贪心】
- RAII&智能指针
- POJ-1273-Drainage Ditches(最大流)dinic实现 后续模板待补充
- Mastering Bitcoin(掌握比特币)读书笔记
- RabbitMQ消息队列(一): Detailed Introduction 详细介绍
- vitualbox + debain 配置NAT+HOSTONY的固定IP
- LeetCode 11 Container With Most Water
- Factorial Trailing Zeroes 带测试版
- LeetCode *** 217. Contains Duplicate
- zoj 1094 Matrix Chain Multiplication
- aircarck-ng
- RAII和模拟实现智能指针
- 微软CEO 纳德拉将赌注押在人工智能上
- Grails如何启动Debug模式
- http://blog.csdn.net/lmj623565791/article/details/39122981