The Solution to Leetcode 605 Can Place Flowers
来源:互联网 发布:七星彩预测软件 编辑:程序博客网 时间:2024/05/22 14:32
Question:
Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.
Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if nnew flowers can be planted in it without violating the no-adjacent-flowers rule.
假设你有一个长的花坛,其中一些地块种植,有些不是。 然而,花朵不能种植在相邻的地块上 - 他们会争取水,两者都会死亡。给定一个花坛(表示为包含0和1的数组,其中0表示空,1表示不为空),数字n,如果可以种植n个新鲜花,则不返回无相邻花规则。
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2Output: False
Note:
- The input array won't violate no-adjacent-flowers rule.
- The input array size is in the range of [1, 20000].
- n is a non-negative integer which won't exceed the input array size.
注意:输入数组不会违反无相邻花规则。
输入数组大小在[1,20000]的范围内。
n是不会超过输入数组大小的非负整数。
思路:首先判断对于给定的数组,能够放多少数字1进去。有两个相邻的数字1就返回false.对于是数字0的元素,要检查左右两边的数字是不是0,如果是0,就可以放1,对于第一个数字,只用判断右边的数字是不是0,对于最后一个数字,只用判断左边的数字是不是0.最后求得一共能放进去1的数字的个数q与输入的n对比,如果q大于等于n,那么就返回true,否则false。
Answer:
class Solution {public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { int i; int q=0; if(flowerbed[0]==0&&flowerbed[1]==0) q=q+1; if(flowerbed[flowerbed.size()-1]==0&&flowerbed[flowerbed.size()-2]==0) q=q+1; for(i==1;i<flowerbed.size()-2;i++) { if(flowerbed[i]==0) { if(flowerbed[i-1]==0&&flowerbed[i+1]==0) { q=q+1; flowerbed[i]==1; } } } if(q>=n) return true; else return false; }};
Run code result:
Your input
[1,0,0,0,1]2
Your answer
false
Expected answer
false
- The Solution to Leetcode 605 Can Place Flowers
- LeetCode 605 : Can Place Flowers
- Leetcode 605 Can Place Flowers
- leetcode[Can Place Flowers]
- leetcode-Can Place Flowers
- leetCode-Can Place Flowers
- LeetCode Can Place Flowers
- leetcode 605[easy]---Can Place Flowers
- 605Can Place Flowers
- [leetcode]605. Can Place Flowers
- [LeetCode]605. Can Place Flowers
- [LeetCode]605. Can Place Flowers
- LeetCode 605.Can Place Flowers
- [leetcode]: 605. Can Place Flowers
- [LeetCode] 605. Can Place Flowers
- LeetCode: 605. Can Place Flowers
- leetcode 605. Can Place Flowers
- LeetCode 605. Can Place Flowers
- Mac OS X下安装并配置JDK
- 如何选择版本控制系统之三
- 更多软件产品
- 位运算 用途
- APT威胁检测之flash类检测方法
- The Solution to Leetcode 605 Can Place Flowers
- Git 常用命令总结
- java.lang.NoClassDefFoundError: net/sf/json/JSONObject异常的解决办法
- 推荐五款Android 应用的自动化测试工具
- JSP内置对象request的方法的使用
- Java版拼图游戏(基于swing编程提升版)
- linux三剑客之grep命令详解
- linux reboot流程
- ReentrantLock学习笔记