题解 | #最大放牛数#

最大放牛数

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

#include <pthread.h>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pasture int整型vector 
     * @param n int整型 
     * @return bool布尔型
     */
    bool canPlaceCows(vector<int>& pasture, int n) {
        // write code here
        int len = pasture.size();
        int count = 0;
        //遍历每一个位置
        for (int i = 0; i < len; i++) {
		  	//如果当前位置有牛,直接下一次循环
            if (pasture[i] == 1) {
                continue;
            } else {
			  	//没有牛时,需要分多中情况讨论
			    //如果当前在第一个位置
                if (i == 0) {
				    //往后还有位置且位置是空的,则可以放一头牛
                    if (i+1<len && pasture[i+1] == 0) {
                        pasture[i] = 1;
                        count++;
					// 往后没有位置了,可以放置一头牛
                    } else if (i+1 == len) {
                        pasture[i] = 1;
                        count++;
                    }
				//在最后一个位置
                } else if (i == len-1) {
				    //往前有位置,且没有牛
                    if (i-1 >= 0 && pasture[i-1] == 0) {
                        pasture[i] = 1;
                        count++;
					//下面这种情况应该是和i=0的第二种情况是重合的,可能不会走到这个分支中
                    } else if (i-1 < 0) {
                        pasture[i] = 1;
                        count++;
                    }
                } else {
				  	//在中间位置,则直接判断前后位置即可
                    if (pasture[i-1] == 0 && pasture[i+1] == 0) {
                        pasture[i] = 1;
                        count++;
                    }
                }
            }
        }
        return count >= n;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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