1. 首页
  2. 软件开发
  3. day-31 给植物浇水

day-31 给植物浇水

  • 发布于 2024-09-26
  • 1 次阅读


思路
每次前进浇水时进行判断:
(1)如果当前水足够,则前进一步浇水
(2)如果当前水量不够,则返回-1处加水再返回,再前进一步浇水

解题方法
用一个变量po记录即将浇水的植物编号,当po==plants.length结束while循环

Code

class Solution {

    public int wateringPlants(int[] plants, int capacity) {

        int step=0;
        int water=capacity;
        int n=plants.length;
        int po=0;
        while(po<n){

            if(water>=plants[po]){

                step++;
                water=water-plants[po];
            }else{

                step=step+po;
                step=step+po+1;
                water=capacity-plants[po];
            }
            po++;
        }
        return step;
    }
}

原文链接: https://blog.csdn.net/qq_53568730/article/details/138617278