Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

605. Can Place Flowers

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

Given an integer array flowerbed containing 0’s and 1’s, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.

Example 1:

1
2
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true

Example 2:

1
2
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
TC: O(n), SC: O(1)  
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 0;
for(int i = 0; i< flowerbed.length;i++){
// find place to put flower
if(flowerbed[i] == 0){
// Not out of bound and can place flower
boolean left = (i - 1 <0 || flowerbed[i-1] == 0);
boolean right = (i + 1 >= flowerbed.length|| flowerbed[i+1] == 0);
if(left && right){
count++;
flowerbed[i]=1;
}
}
}
return count >= n;
}
}

198. House Robber


如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels