LeetCode(11) Container With Most Water
来源:互联网 发布:珠海公司拖欠工资知想 编辑:程序博客网 时间:2024/05/14 02:03
一开始使用动态规划来解决这道问题:
将可行解分为两类,一类为包含8号线,一类为不包含8号线;
将8号线依次与0~7号线配对,求出包含8号线的那一类可行解的最大值;
如果已经知道不包含8号线的最大值,即前七条线中的最大值,一个较小的子问题的解;
比较上两步中的最大值,即得结果。
#include<iostream>#include<vector>using namespace std;class Solution {public: int maxArea(vector<int>& height) { int length = height.size(); int *arr = new int[length]; arr[0] = 0; arr[1] = min(height[0], height[1]) * 1; for(int i = 2; i < height.size(); i++) { int maxArea = 0; for(int j = 0; j < i; j++) { if(min(height[i], height[j]) * (i - j) > maxArea) maxArea = min(height[i], height[j]) * (i - j); } if(maxArea > arr[i - 1]) arr[i] = maxArea; else arr[i] = arr[i - 1]; } //for(int i = 0; i < height.size(); i++) //cout << arr[i] << endl; return arr[height.size() - 1]; }};int main() { Solution solution; vector<int> height; height.push_back(3);height.push_back(2);height.push_back(5);height.push_back(3); height.push_back(4);height.push_back(2);height.push_back(1);height.push_back(1); //solution.maxArea(height); cout << solution.maxArea(height) << endl; getchar();}
结果是超时,最后看到网上有o(n)的解法,其实不大看的懂,哈哈,代码如下:
class Solution {public: int maxArea(vector<int>& height) { int left = 0; int right = height.size() - 1; int max = min(height[left], height[right]) * (right - left); int tmp; while(left < right) { if(height[left] < height[right]) { left++; max = max > min(height[left], height[right]) * (right - left) ? max : min(height[left], height[right]) * (right - left); }else { right--; max = max > min(height[left], height[right]) * (right - left) ? max : min(height[left], height[right]) * (right - left); } } return max; }};
上面的代码参考这里
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
- leetcode 11 Container With Most Water
- leetcode-11 Container With Most Water
- Container With Most Water - LeetCode 11
- [Leetcode 11, Medium] Container With Most Water
- 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-11Container With Most Water
- leetcode 11 -- Container With Most Water
- Fedora(Linux)中配置mondodb数据库
- ZigZag Conversion
- c语言中scanf 与 fgets的区别 以及怎么同时用两个函数
- listview中的item增加事件
- UI基础之------UITableView高级
- LeetCode(11) Container With Most Water
- 自己动手写MutableArray
- FFmpeg参数
- addClass
- HDU1032 The 3n + 1 problem
- 为什么静态类不能访问非静态类
- 【LintCode】Search Insert Position 搜索插入位置
- 第五天的笔记
- C语言基础6