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,两个的运行空间基本一样。
  • 相关阅读:
    构建之法阅读笔记01
    学习进度13
    学习进度12
    个人冲刺十
    个人冲刺九
    个人冲刺八
    学习进度11
    个人冲刺七
    个人冲刺六
    [HDU 1232 ]畅通工程
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/14219825.html
Copyright © 2011-2022 走看看