20211201:力扣第268周双周赛(上)

力扣第268周双周赛(上)

题目

    1. 两栋颜色不同且距离最远的房子
      在这里插入图片描述
    1. 给植物浇水
      在这里插入图片描述

思路与算法

  1. 双指针遍历即可,维护那个索引最大差值即可。
  2. 模拟题,正常情况需要每次走一步即可灌溉,碰到水不够的情况需要灌满水回到原地的步数,维护这个步数,注意索引不要越界。最后一步只需要考虑灌满,不需要考虑需不需要回去装满水。

代码实现

    1. 两栋颜色不同且距离最远的房子
class Solution {
public:
    int maxDistance(vector<int>& colors) {
        int ans = 0;
        int len = colors.size();
        for (int i = 0; i < len - 1; ++i) {
            for (int j = i + 1; j < len; ++j) {
                if(colors[i] != colors[j])
                    ans = max(abs(j - i),ans);
            }
        }
        return ans;
    }
};
    1. 给植物浇水
class Solution {
public:
    int wateringPlants(vector<int>& plants, int capacity) {
        int len = plants.size();
        int sum = 0;
        int ans = 0;
        for (int i = 0; i < len - 1; ++i) {
            sum += plants[i];
            ans += 1;
            if (sum <= capacity && sum + plants[i+1] > capacity) {
                sum = 0;
                ans += (2*i+2);
            } 
        }
        return ans+1;
    }
};

写在最后

  1. 认真准备论文开题,可以开始着手找工作的准备了。

版权声明:本文为qq_36828395原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。