zoukankan      html  css  js  c++  java
  • 605. 种花问题

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

    给定一个花坛(表示为一个数组包含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;
        }
    }
  • 相关阅读:
    2171 棋盘覆盖
    [网络流24题] 骑士共存
    COGS28 [NOI2006] 最大获利[最大权闭合子图]
    1066: [SCOI2007]蜥蜴
    1877: [SDOI2009]晨跑
    POJ 2125 Destroying the Graph 二分图最小点权覆盖
    LA 3231
    3028: 食物
    PYOJ 44. 【HNSDFZ2016 #6】可持久化线段树
    1597: [Usaco2008 Mar]土地购买
  • 原文地址:https://www.cnblogs.com/zzxisgod/p/13338790.html
Copyright © 2011-2022 走看看