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:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
난이도: easy
꽃이 심어져 있는 화단이 있다, 0
은 안심어져있는 곳, 1
은 이미 심어져 있는 곳
주변에 꽃이 심어져있지 않은 곳에만 꽃을 심을 수 있다
n이 주어졌을 때, n개의 숫자만큼 심을 수 있는지 판단해라
var canPlaceFlowers = function(flowerbed, n) {
let flowerCount = 0;
for (let i = 0; i < flowerbed.length; i++) {
if (!flowerbed[i - 1] && !flowerbed[i] && !flowerbed[i + 1]) {
flowerbed[i] = 1
flowerCount++
}
}
return flowerCount >= n
};
처음에는 화단의 끝부분일 경우와 중간에 심는 경우 두가지로 나누어서 생각했고,
통과를 하는데 너무 많은 조건이 붙기에, 자바스크립트에서 Array에 존재하지 않는 index를 불러올 경우
어떻게 되는지 확인 후, 다시 풀었다
풀고나니 되게 별거 아니어서 좀 허탈하네
easy난이도 100개정도는 풀어보고 medium으로 얼른 넘어가봐야겠다
반응형
'Algorithm' 카테고리의 다른 글
[Leetcode] 2144. Minimum Cost of Buying Candies With Discount (0) | 2022.03.07 |
---|---|
[Leetcode] 1160. Find Words That Can Be Formed by Characters (0) | 2022.03.06 |
[Leetcode] 155. Min Stack (0) | 2022.03.05 |
[Leetcode] 1306. Jump Game III (0) | 2022.03.04 |
[Leetcode] 860. Lemonade Change (0) | 2022.03.04 |