1. 程式人生 >實用技巧 >其它 >【LeetCode605】-種花問題

【LeetCode605】-種花問題


技術標籤:LeetCode刷題leetcode貪心演算法

方法一

實現思路

就是儘量靠最左邊或靠最優邊種花,如果不可行儘量在前面只隔一個種花

實現程式碼

class Solution {
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
        if(flowerbed.size()==1&&!flowerbed[0]&&n<=1) return true;
        for(int i=1;i<flowerbed.size();i++){
            if(n==0) break;
            if(!flowerbed[i-1]&&!flowerbed[i]){
                if(i==flowerbed.size()-1||i==1)
                {
                    int index=i;
                    if(i==1) index=index-1;
                    flowerbed[index]=1;
                    n--;
                }
                else if(!flowerbed[i+1]){
                    flowerbed[i]=1;
                    n--;
                }
                
            }
            
        }
        return !n;
    }
};

提交結果及分析

【LeetCode605】-種花問題


時間複雜度O(n)

方法二

實現思路

為了方便統一化處理,可以在頭新增一個0,尾新增一個0,那樣就可以實現判斷一個元素左右兩邊及自己都為0,就可以在自己的位置種花
從左到右遍歷,能種就種