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;
    }
    };

    加油!

  • 相关阅读:
    2021/9/20 开始排序算法
    快速排序(自己版本)
    2021/9/17(栈实现+中后缀表达式求值)
    2021/9/18+19(中缀转后缀 + 递归 迷宫 + 八皇后)
    20212021/9/13 稀疏数组
    2021/9/12 线性表之ArrayList
    开发环境重整
    Nginx入门
    《财富的帝国》读书笔记
    Linux入门
  • 原文地址:https://www.cnblogs.com/bestwangjie/p/4454841.html
Copyright © 2011-2022 走看看