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

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

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<flowerbed.length;i++) {        		if(i==0)        			if(flowerbed[i]!=1&&flowerbed[i+1]!=1) {        			count++;        			flowerbed[i]=1;        		}        		if(i==flowerbed.length-1)        			if(flowerbed[i-1]!=1&&flowerbed[i]!=1) {        			count++;        			flowerbed[i]=1;        		}        		if(i!=0&&i!=flowerbed.length-1) {        			if(flowerbed[i]!=1&&flowerbed[i-1]!=1&&flowerbed[i+1]!=1) {        				count++;            			flowerbed[i]=1;        			}        		}        	}        	if(count>=n)        		return true;        	else        		return false;        	}        	        }    }}

​后记

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

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

你可能感兴趣的文章
字符串详解
查看>>
焦点事件
查看>>
webpack打包常见报错
查看>>
vuex—1vuex初始
查看>>
axios服务器通信—1axios介绍和使用mock数据
查看>>
web前端面试一从输入url到看到页面发生了什么
查看>>
关于IP地址
查看>>
IO复用之epoll
查看>>
智慧水利的泵站自动化监控系统解决方案
查看>>
C getopt.h
查看>>
TensorRT/parsers/caffe/caffeParser/caffeParser.h源碼研讀
查看>>
PCL MLS論文Computing and Rendering Point Set Surfaces研讀筆記
查看>>
CentOS下Nvidia docker 2.0之安裝教程&踩坑實錄
查看>>
PIL及matplotlib:OSError: cannot identify image file錯誤及解決方式
查看>>
H5页面授权获取微信授权(openId,微信nickname等信息)
查看>>
SpringBoot的URL是如何拼接的
查看>>
2018年年终总结
查看>>
解决checkbox未选中不传递value的多种方法
查看>>
【pgsql-参数详解1】PostgreSQL默认参数值
查看>>
PostgreSQL11-Hash哈希分区数量的设定标准
查看>>