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

    题目链接:605.种花问题

    思路:贪心。题解有点没认真看,不知道是啥意思。自己的思路很简单,就是判断当前位置能不能放,能就放,不能就判断下一个位置。

    代码:

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

    笔记

    • 使用迭代算法的运行时间为2ms,使用循环的时间为1ms,两个的运行空间基本一样。
  • 相关阅读:
    轻量级锁和偏向锁等
    桥接模式
    适配器模式
    建造者模式
    2-工厂模式
    Swift
    给视图添加点击波纹效果swift5
    Xcode 支持真机版本路径
    22个常用开源库(most swift)
    Github上关于iOS的各种开源项目集合
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/14219825.html
Copyright © 2011-2022 走看看