zoukankan      html  css  js  c++  java
  • LeetCode 11 Container With Most Water

    题目如下:

    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.

    翻译略去,直接说思路,刚开始我想错了,直接想成了计算题型面积(a[j]-a[i])*(j-i)/2,而且还用了个穷举法。

    这里应该计算并比较min(h[i], h[j]) * (j - i)。

    选择从两端到中间递归查找,程序如下:

    class Solution {
    public:
       int maxArea(vector<int> &height)
    {
        int ret = findMax(height, 0, height.size()-1, 0);
        return ret;
    }
    int findMax(vector<int> &h, int i , int j , int area)
    {
        int temp = 0;
    
        if(i == j)
        {
            cout << i << " " << j << endl;
            return area;
        }
    
        temp = (h[i]>h[j]?h[j]:h[i]) * (j - i) ;
        if(h[i] > h[j])
        {
            j -= 1;
        }
        else
        {
            i += 1;
        }
        if(temp < area)
            findMax(h, i, j , area);
        else
            findMax(h, i, j, temp);
    }
    };

    非递归版本:

    class Solution {
    public:
       int maxArea(vector<int> &height)
    {
        int area = 0;
        int iStart = 0;
        int iEnd = height.size()-1;
        vector<int> h = height;
    
        while(iStart != iEnd)
        {
            int temp = (h[iStart] > h[iEnd]?h[iEnd]:h[iStart]) * (iEnd - iStart);
            if(temp > area)
            {
                area = temp;
            }
            if(h[iStart] > h[iEnd])
            {
                iEnd -= 1;
            }
            else
            {
                iStart += 1;
            }
        }
        return area;
    }
    };

    加油!

  • 相关阅读:
    kafka原理深入研究 (转 )
    redis——持久化篇
    IDEA 配置环境和相关工具整理(新手入门)
    Spring Data JPA(官方文档翻译)
    springboot:spring data jpa介绍
    JDK8-十大新特性-附demo
    JDK8新特性一览
    Maven中的pom.xml配置文件详解
    数据库面试题(更新中...)
    互联网协议系列
  • 原文地址:https://www.cnblogs.com/bestwangjie/p/4454841.html
Copyright © 2011-2022 走看看