博客
关于我
LeetCode刷题记录8——605. Can Place Flowers(easy)
阅读量:539 次
发布时间:2019-03-08

本文共 1044 字,大约阅读时间需要 3 分钟。

LeetCode刷题记录8——605. Can Place Flowers(easy)

目录


题目

题目说给定一个数组,数组中只有0或1,1代表此处种了花,0代表此处空闲不种花。种花的规则是相邻之间不能种花,只能隔一下种一个。给定一个整数n,代表这个数组还能种多少多花,如果能种的下n朵,就返回true;否则返回false。

语言

Java、C++(算法用的一模一样,只是换了一种语言)

思路

整体思路:遍历整个数组,发现能种花的地方,用count累加计数。

大体先分两种情况:

  1. 如果n=0,那么肯定返回true,因为种0朵当然能种下。

  2. 当n不为0时:

    1. 如果数组长度为0,则返回false

    2. 如果数组长度为1,并且这个值为1,返回false;否则返回true

    3. 如果数组长度大于1:

      1. 考虑开头:i=0,如果下标为0和1的值均不为1,则count++,并且值置为1

      2. 考虑结尾:i=length-1,如果下标length-1和length-2的值均不为1,count++,并且值置为1

      3. 剩余情况:当这个值不为1,且前一个和后一个均不为1时,count++,并且值置为1

    最终将count与输入的n对比,如果count>=n,则返回true;否则返回false。

源码

class Solution {    public boolean canPlaceFlowers(int[] flowerbed, int n) {        if(n==0)        	return true;        else {        	int count=0;        	if(flowerbed.length==0) return false;        	else if(flowerbed.length==1) {        		if(flowerbed[0]==1) return false;        		else return true;        	}        	else {        		for(int i=0;i
=n) return true; else return false; } } }}

​后记

其实做这题的主要是要看懂题目中的adjacent 是啥意思,这是相邻的意思,如果这个理解错了,后面就凉凉。

转载地址:http://foyiz.baihongyu.com/

你可能感兴趣的文章
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>
mysql CPU使用率过高的一次处理经历
查看>>
Multisim中555定时器使用技巧
查看>>
MySQL CRUD 数据表基础操作实战
查看>>
multisim变压器反馈式_穿过隔离栅供电:认识隔离式直流/ 直流偏置电源
查看>>
mysql csv import meets charset
查看>>
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>
MySQL DBA 数据库优化策略
查看>>
multi_index_container
查看>>