-
[LeetCode] 605. Can Place FlowersLeetCode 2022. 1. 18. 10:25728x90
https://leetcode.com/problems/can-place-flowers/
Can Place Flowers - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Can Place Flowers - Easy

화분이 줄지어 있다.
0은 꽃이 심어지지 않은 화분, 1은 꽃이 심어진 화분이다.
화분에 꽃을 심는데, 양쪽이 비어있는 화분에만 꽃을 심을 수 있다.
이 때 주어진 n송이의 꽃을 심을 수 있는지 구하는 문제다.
화분을 앞에서 부터 훑으며, 해당 화분, 전 화분, 이후의 화분이 모두 0이면 1로 바꾸고, 심어진 꽃의 수를 1씩 늘린다.
이후 심어진 꽃 수가 n이상인지 판단하면 된다.
화분 개수가 1인 경우와 인덱스가 0인경우, 마지막인 경우에 주의하자.
전체 풀이 코드
class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { int ret = 0, s = flowerbed.size(); if (!flowerbed[0] && (s==1 || (1<s && !flowerbed[1]))) flowerbed[0]=1, ret++; for (int i=1; i<flowerbed.size()-1; i++) if (!flowerbed[i] && !flowerbed[i-1] && !flowerbed[i+1]) flowerbed[i]=1,ret++; if (1<flowerbed.size() && !flowerbed[s-2] && !flowerbed[s-1]) flowerbed[s-1]=1, ret++; return ret>=n; } };'LeetCode' 카테고리의 다른 글
[LeetCode] 134. Gas Station (0) 2022.01.21 [LeetCode] 875. Koko Eating Bananas (0) 2022.01.20 [LeetCode] 290. Word Pattern (0) 2022.01.17 [LeetCode] 452. Minimum Number of Arrows to Burst Balloons (0) 2022.01.13 [LeetCode] 701. Insert into a Binary Search Tree (0) 2022.01.12