• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
正在努力成为一个优秀的废物
博客园    首页    新随笔    联系   管理    订阅  订阅
C++LeetCode:: Container With Most Water

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

题目:

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

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

posted on 2018-02-28 14:42  你算哪根小毛线  阅读(134)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3