zoukankan      html  css  js  c++  java
  • 【leetcode】Container With Most Water(middle)

    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.

    Note: You may not slant the container.

    思路:

    肯定是要确定水槽的左右边界位置,需要两个变量l1,l2 分别从最左边和最右边收缩。收缩规则是,比较矮的那一边向中间靠拢。更新水量。

    我自己的代码:

    int maxArea(vector<int> &height) {
            int ans = (height.size() - 1) * min(height[0], height.back()) ;
            int l1, l2, h1, h2;
            h1 = 0; h2 = height.size() - 1;
            l1 = h1; l2 = h2;
            while(l1 < l2)
            {
                if(height[l1] > height[h1])
                {
                    h1 = l1;
                    int tmp = (l2 - l1) * min(height[l2], height[l1]);
                    ans = (tmp > ans) ? tmp : ans;
                }
                if(height[l2] > height[h2])
                {
                    h2 = l2;
                    int tmp = (l2 - l1) * min(height[l2], height[l1]);
                    ans = (tmp > ans) ? tmp : ans;
                }
                if(height[l1] < height[l2])
                {
                    l1++;
                }
                else if(height[l1] > height[l2])
                {
                    l2--;
                }
                else
                {
                    l1++; l2--;
                }
            }
            return ans;
        }

    大神的代码就简洁很多:

    int maxArea(vector<int> &height) {
        int left = 0, right = height.size() - 1;
        int maxWater = 0;
        while(left < right){
            maxWater = max(maxWater, (right - left) * min(height[left], height[right]));
            height[left] < height[right] ? left++ : right--;
        }
        return maxWater;
    }
  • 相关阅读:
    个人阅读作业Week7
    个人博客作业week3——案例分析
    结对项目——高级四则运算检验器记录(168 & 187)
    个人博客作业week2——代码复审
    个人项目---四则运算题目生成器项目记录
    第一次博客作业
    JAVA编程入门
    计算机基础知识点总结
    Java数据类型总结1
    JAVA编程入门
  • 原文地址:https://www.cnblogs.com/dplearning/p/4275912.html
Copyright © 2011-2022 走看看