본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 605. Can Place Flowers

반응형

https://leetcode.com/problems/can-place-flowers/description/

 

Can Place Flowers - LeetCode

Can you solve this real interview question? 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'

leetcode.com

simulation 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 심은 행위의 개수 plantedCnt와 편한 비교를 위해 flowerbed를 옮길 vector fb를 선언해줍니다.2. 양 옆을 확인하기 위해 flowerbed의 양끝에 0을 추가해 fb에 저장해줍니다.

📔 풀이과정

for loop를 수행해줍니다.

인접한 곳에 꽃이 심어져 있지않다면 꽃을 심고 plantedCnt를 1더해줍니다.

📔 정답 출력 | 반환

plantedCnt가 n이상인지 여부를 반환해줍니다.


📕 Code

📔 C++

class Solution {
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
        int plantedCnt = 0;
        vector <int> fb = {0};
        fb.insert(fb.end(), flowerbed.begin(), flowerbed.end());
        fb.push_back(0);
        for(int i = 1; i < fb.size()-1; i++) {
            if(fb[i]) continue;
            if(!fb[i-1] && !fb[i+1]) {
                plantedCnt++;
                fb[i] = 1;
            }
        }
        return plantedCnt >= n;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.