LeetCode#11. Container With Most Water

题意:Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值