思考: 1.可以放花的條件 左邊0 右邊0 且自身為 0 2.讀取到超出index的問題,如果是首位則沒有左,如果是末位則沒有右 3.由 i == 首位or末位開始判斷 可以解決讀取到超出範圍index的問題,因為or判斷中 只要前面 true 就不判斷後面了,所以不讀取超出範圍的index。 判斷邏輯: 1.flowerbed[i] == 0:表示在第 i 個位置是空的,可以種植花朵。 2.(i == 0 || flowerbed[i - 1] == 0):表示要在第 i 個位置種植花朵,需要滿足兩個條件之一: (1) i == 0:即 i 是第一個位置,這樣就不需要檢查前一個位置是否有花朵,因為不存在前一個位置。 (2) flowerbed[i - 1] == 0:表示第 i 個位置的前一個位置是空的,也就是說前一個位置可以種植花朵。 3.(i == fool-1 || flowerbed[i + 1] == 0):表示要在第 i 個位置種植花朵,需要滿足兩個條件之一: (1) i == fool-1:即 i 是最後一個位置,這樣就不需要檢查後一個位置是否有花朵,因為不存在後一個位置。 (2) flowerbed[i + 1] == 0:表示第 i 個位置的後一個位置是空的,也就是說後一個位置可以種植花朵。 ```c++= class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { // 首先要自己是 0 才開始考慮 // 非首位才有左點 // 非末位才有右點 // (i == 0 || flowerbed[i - 1] == 0) 和 ( i == (plot -1) || flowerbed[i + 1] == 0) // 由 i == 首位or末位開始判斷 可以解決讀取到超出範圍index的問題,因為or判斷中 只要前面 true 就不判斷後面了,所以不讀取超出範圍的index int plot = flowerbed.size(); for(int i = 0; i < plot; i++){ if( (flowerbed[i] == 0) && (i == 0 || flowerbed[i - 1] == 0) && ( i == (plot -1) || flowerbed[i + 1] == 0)){ n--; flowerbed[i] = 1; } } return n <= 0; } }; ``` ```javascript= /** * @param {number[]} flowerbed * @param {number} n * @return {boolean} */ var canPlaceFlowers = function(flowerbed, n) { for(let i = 0; i < flowerbed.length; i++){ if(flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == (flowerbed.length-1) || flowerbed[i + 1] == 0)){ n--; flowerbed[i] = 1; if(n === 0){ return true; } } } return n <= 0; }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up