您的位置:首页 > 大数据 > 人工智能

leetcode11 Container With Most Water

2015-09-27 19:40 411 查看
题意:题的大概意思就是给你一个数组,数组中数字是无序的,每一个数代表一条垂直x轴的线,数值代表长度,问哪两条线和x轴中间的面积最大,题中是说最多能放多少水.

我这翻来覆去一想,这n^2遍历一遍就都知道了,但这个复杂度有点不对啊,至少也应该是一个n*logn或者n的时间复杂度啊,最后看了一下discuss果不其然啊,真的是有n的解法.

其实就是利用贪心的原理,往左缩一位或者往右缩一位,下面贴出源码,就几行代码.

#include "stdio.h"
#include "iostream"
#include "math.h"
#include "vector"
using namespace std;

class Solution {
public:
    int maxArea(vector<int>& height) {
		
    	int temp;
    	int left = 0,right = height.size()-1;
    	int result = 0;
    	while(left<right)
    	{
    		result = max(result,min(height[left],height[right])*(right-left));
    		if(height[left]<height[right])
    			left++;
    		else
    			right--;
    	}
    	return result;
    }
};

int main()
{

	vector<int> num;
	Solution test;
	int result;
	num.push_back(2);
	num.push_back(5);
	num.push_back(5);
	num.push_back(2);
	num.push_back(3);
	num.push_back(2);

	result = test.maxArea(num);
	cout<<result<<endl;

	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: