Leetcode 605. Can Place Flowers(Easy)
2018-03-27 10:10
525 查看
1.题目
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 n new flowers can be planted in it without violating the no-adjacent-flowers rule.Example 1:Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: False翻译:假如你有一个很长的花床,有一些坑儿被种植了花,有些没有。然而,花不能被种在相邻的坑里,它们会因为竞争水而都死掉。给定一个花床(用0.1序列表示,0代表坑儿是空的,1代表已经种植了花),和一个数字n,返回在遵循不相邻种花的原则下,n朵新花能否被种植。
2.思路
这个题真的是碎,折腾我好久。改来改去,总结起来,有三种模式。用zero_temp表示连续的0的个数。①在两个1中间,有几个连续的0,就能种 (zero_temp-1)/2朵花。
②在第一个1之前,有几个连续的0,能种zero_temp/2朵花。
③对于,最后一组连续的0。如果从未出现过1,能种zero_temp/2向上取整朵花;如果出现过1,能种zero_temp/2朵花。
然后能种的花朵数,大于等于n,即代表可以种下。
3.算法
class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int count=0; int zero_temp=0; double temp; int flag=0;//没碰到1 for(int i=0;i<flowerbed.length;i++){ if(flowerbed[i]==0){ zero_temp++; }else if(flowerbed[i]==1){ if(flag==0){ count+=zero_temp/2; flag=1; zero_temp=0; } else if(flag==1&&zero_temp!=0){ count+=(zero_temp-1)/2; if(count>=n)return true; zero_temp=0; } } } if(zero_temp!=0){ if(flag==0){ temp=(double)zero_temp/2; count+=Math.ceil(temp); }else { count+=(zero_temp)/2; } } if(count>=n)return true; else return false; } }
4.总结
向上取整 Math.ceil(); 在本题中我使用了Math.ceil(zero_temp/2);这样是不行的,zero_temp是int型的,int型除以2的过程中保留的已经是向下取整之后的结果了。所以先把int转为double型,再进行向上取整。Math.ceil()向上取整;
Math.floor()向下取整;
Math.round()四舍五入取整。
相关文章推荐
- leetcode 605[easy]---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(Python & C++)
- [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@Array_605_Can_Place_Flowers
- LeetCode 605. Can Place Flowers (可以种花)
- [leetcode]: 605. Can Place Flowers
- leetcode 605. Can Place Flowers python
- leetcode 605. Can Place Flowers