ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

605. 种花问题

2020-07-19 10:00:54  阅读:266  来源: 互联网

标签:605 int flowerbed else 问题 ++ length 种花 &&


假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。

给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。

示例 1:

输入: flowerbed = [1,0,0,0,1], n = 1
输出: True

示例 2:

输入: flowerbed = [1,0,0,0,1], n = 2
输出: False

注意:

  • 数组内已种好的花不会违反种植规则。
  • 输入的数组长度范围为 [1, 20000]。
  • n 是非负整数,且不会超过输入数组的大小。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/can-place-flowers


思路:

只要回答能不能种下就行,那就把能种下的情况都试一下,每次种下一朵就0变1,计数器+1

最终的计数结果和n比较一下,搞定

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
    int len = flowerbed.length;
    int cnt = 0;
    for (int i = 0; i < len && cnt < n; i++) {
        if (flowerbed[i] == 1) {
            continue;
        }
        int pre = i == 0 ? 0 : flowerbed[i - 1];
        int next = i == len - 1 ? 0 : flowerbed[i + 1];
        if (pre == 0 && next == 0) {
            cnt++;
            flowerbed[i] = 1;
        }
    }
    return cnt >= n;
}
}

Solution Two (第一个是参考别人的,第二个是我写的,发现了,还是有差距的)

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int count = 0;
        if (flowerbed.length == 1 && flowerbed[0] == 0){
            count++;
        }else {
            for (int i = 0; i < flowerbed.length; i++) {
                if (i ==0 && flowerbed[0] == 0 && flowerbed[1] == 0 ){
                    flowerbed[i] = 1;
                    count ++;
                }else if (i ==0 && flowerbed[0] == 0 && flowerbed[1] == 1){
                    continue;
                }
                else if(i == flowerbed.length-1 && flowerbed[flowerbed.length-1] == 0 && flowerbed[flowerbed.length-2] == 0){
                    flowerbed[flowerbed.length - 1] = 1;
                    count ++;
                }else if (i == flowerbed.length-1 && flowerbed[flowerbed.length-1] == 0 && flowerbed[flowerbed.length-2] == 1){
                    continue;
                }
                else if(flowerbed[i] == 0 && flowerbed[i-1] ==0 && flowerbed[i + 1] == 0){
                    flowerbed[i] = 1;
                    count++;
                }else {
                    continue;
                }
            }
        }
        return count >= n;
    }
}

 

标签:605,int,flowerbed,else,问题,++,length,种花,&&
来源: https://www.cnblogs.com/zzxisgod/p/13338790.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有