博客
关于我
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/

你可能感兴趣的文章
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx/Apache反向代理
查看>>
Nginx: 413 – Request Entity Too Large Error and Solution
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:
查看>>
nginx: [error] open() “/usr/local/nginx/logs/nginx.pid“ failed (2: No such file or directory)
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
Nginx:objs/Makefile:432: recipe for target ‘objs/src/core/ngx_murmurhash.o‘解决方法
查看>>
nginxWebUI runCmd RCE漏洞复现
查看>>
nginx_rtmp
查看>>
Vue中向js中传递参数并在js中定义对象并转换参数
查看>>
Nginx、HAProxy、LVS
查看>>
nginx一些重要配置说明
查看>>
Nginx一网打尽:动静分离、压缩、缓存、黑白名单、跨域、高可用、性能优化......
查看>>
Nginx下配置codeigniter框架方法
查看>>
Nginx与Tengine安装和使用以及配置健康节点检测
查看>>
Nginx中使用expires指令实现配置浏览器缓存
查看>>
Nginx中使用keepalive实现保持上游长连接实现提高吞吐量示例与测试
查看>>
Nginx中如何配置WebSocket代理?
查看>>