题解 | #最大放牛数#

最大放牛数

https://www.nowcoder.com/practice/5ccfbb41306c445fb3fd35a4d986f8b2

知识点

模拟,贪心

思路

当i与i-1位置都为0时,这个位置0变为1,同时n--。

特判:i=0且i位置为0时,也要将这个位置变为1,同时n--。

最后当n<=0,可以返回true。否则返回false

代码c++

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pasture int整型vector 
     * @param n int整型 
     * @return bool布尔型
     */
    bool canPlaceCows(vector<int>& pasture, int n) {
        // write code here
        int t=0;
        int ans=0;
        for(int i=0;i<pasture.size()&&n;i++)
        {     if(i==0&&pasture[i]==0)
               {pasture[i]=1;
                n--;
               }
              else if(pasture[i-1]==0&&pasture[i]==0)
              {
                pasture[i]=1;
                n--;
              }
        }

        if(!n)return true;
        else return false;
    }
};
全部评论

相关推荐

11-15 16:33
已编辑
微软_sde(实习员工)
点赞 评论 收藏
分享
安静的鲸鱼offer...:神仙级别hr,可遇不可求,甚至他可能也是突然有感而发。只能说遇上是件幸事。
秋招开始捡漏了吗
点赞 评论 收藏
分享
09-29 15:34
已编辑
北京航空航天大学 C++
做个有文化的流氓:结果是好的,过程不重要,而且你的offer太多了
软开人,秋招你打算投哪些...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务