Open songyy5517 opened 4 months ago
Approach: Loop through the array & Greedy Algorithm
num_slot
to store the number of the plantable positions;n <= num_slot
.Complexity Analysis
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
// Intuitioin: Find the slots that are isolated in the array.
// 1. Exception handling
if (flowerbed == null || flowerbed.length == 0 || n < 0)
return false;
// 2. Calculate the number of isolated slot
int num_slot = 0;
for (int i = 0; i < flowerbed.length; i++){
if (flowerbed[i] == 0){
if ((i > 0 && flowerbed[i - 1] == 1) || (i < flowerbed.length - 1 && flowerbed[i + 1] == 1))
continue;
flowerbed[i] = 1;
num_slot ++;
}
}
return n <= num_slot;
}
}
2024/5/8
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 true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.
Example 1:
Example 2:
Intuition This problem mainly examines the operations of arrays. We need to plant the flowers as many as possible under the adjacency rule, therefore we can use Greedy Algorithm to solve this problem. Specifically, we loop through the array and determine whether each position is plantable. If so, then we update the number of qualified positions, and set the value of this position to 1; If not, then just move to the next position.