【Leetcode】605. Can Place Flowers(Easy)

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()四舍五入取整。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值