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

    本来写的题目不是这个,而是字符串匹配,考虑了很多情况写了很久最后看了solution,发现可以用动态规划做。感觉被打击到了,果断先放着重新写一个题,后面心情好了再重新写吧,难过。每天都要被LeetCode打击一次。自“抱”自“泣”,逻辑推理能力太差了。

    题目:

    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 and n is at least 2.

    面积取决于两个因素,一个是两个点的横坐标差值,另一个是两个点中的最小值。设置两个指针,分别表示数组的头和尾,首先计算这两个点的所构成长方形的面积,然后移动两点中较小数的指针向前(头指针)或退后(尾指针),因为如果移动的是两点中较大那个数的指针的话,两个点横坐标变小,两个点中最小值变小或者不变,那么长方形面积肯定变小,这样的计算是多余的。重复上述过程知道首尾指针相遇,记录该过程中的面积最大值就是结果。

    class Solution {
    public:
        int maxArea(vector<int>& height) {
            int i = 0, j = height.size()-1;
            int current = 0, bigest = 0;
            while(i<j){
                current = (j-i) * (height[i]>height[j]?height[j--]:height[i++]);
                bigest = bigest>current?bigest:current;
            }
            return bigest;
        }
    };
    

      看了一下运行最快的代码,思路一样,估计测试用例不一样导致运行时间不一样。

  • 相关阅读:
    Bootstrap组件福利篇 网址
    <a>标签中的href="javascript:;"
    HTTP请求上下文之终结:HttpContext类
    数据库分离 附加 sqlserver
    C#中三层架构UI、BLL、DAL、Model实际操作(转)
    比较好的网上的sqlserver读书笔记
    ORACLE重建索引详解
    SQL Server遍历表的几种方法(转)
    提高数据库操作的效率(转)
    哈希表Hashtable与字典表Dictionary<K,V>的比较。
  • 原文地址:https://www.cnblogs.com/catpainter/p/8483535.html
Copyright © 2011-2022 走看看