[贪心法]leetcode5318:灌溉花园的最少水龙头数目(hard)

题目:

5318. 灌溉花园的最少水龙头数目

题解:

  • 贪心法
  • 1:首先遍历rangs,建立45. 跳跃游戏 Ⅱ中的跳跃数组,left表示起始点,right-left表示最大跳跃距离
  • 2:使用跳跃游戏Ⅱ中的代码即可,不过每次到达边界end,需判断furthest是否超过end

代码如下:

class Solution {
public:
    //题解:贪心法
    //1:首先遍历rangs,建立跳跃游戏Ⅱ中的跳跃数组,left表示起始点,right-left表示最大跳跃距离
    //2:使用跳跃游戏Ⅱ中的代码即可,不过每次到达边界end,需判断furthest是否超过end
    int minTaps(int n, vector<int>& ranges) {
        //1、建立跳跃数组
        vector<int> jumps(n+1);
        for(int i=0;i<n+1;++i){
            int left=max(i-ranges[i],0);
            int right=min(i+ranges[i],n);
            if(jumps[left]<right-left){
                jumps[left]=right-left;
            }
        }
        //2、贪心法跳跃
        int furthest=0,end=0,count=0;
        for(int i=0;i<n;++i){//注意最后一个点不能遍历,因为在i==end==0时,count多统计了一次
            furthest=max(jumps[i]+i,furthest);
            if(furthest>=n){
                count++;
                break;
            }
            if(i==end){
                //若最远距离没有超过边界,直接返回-1
                if(furthest<=end)return -1;
                count++;
                end = furthest;
            }
        }
        return count;
    }
};
发布了484 篇原创文章 · 获赞 149 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_43152052/article/details/104045718