Game Tech Blog

605. Can Place Flowers 본문

Algorithm/LeetCode

605. Can Place Flowers

jonghow 2023. 7. 10. 01:28
반응형

[문제]

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.

 

[TC]

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

Constraints:

  • 1 <= flowerbed.length <= 2 * 104
  • flowerbed[i] is 0 or 1.
  • There are no two adjacent flowers in flowerbed.
  • 0 <= n <= flowerbed.length

[접근]

문제는, 쉽게 보면 내 앞과 뒤 인덱스를 검색해서 1이 없는쪽에 내 화분에 꽃을 심을 수 있으니 여기서 준 화분 array 와 n 이라는 카운트가 성립하는지 찾으시오! 라는 문제 유형이다.

보자마자 바로 떠올린건 내 앞과 뒤를 검색해서 1이 안나오면 되잖아? 라는 식으로 접근, 

[1,0,0,0,0,1] 의 케이스를 발견하여, 성립하는 조건이 나온경우 AcceptCount만 올리는게 아니라, 그자리에 꽃을 둔다는 가정을 사용하여 문제 풀이 접근

이후, [0] 또는 [0,0,1,0,0] 인데 n 을 최대로 꽂을 수 있는 화단의 수보다 적게 주는 케이스들을 확인하여, 예외로 적용.

최종 문제 accepted 

 

[코드] C#

public class Solution {
    public bool CanPlaceFlowers(int[] flowerbed, int n) {

        int AcceptCount = 0;

        if(flowerbed.Length == 1 && flowerbed[0] == 0)
            ++AcceptCount;    
        else
        {
            for(int i = 0; i < flowerbed.Length; ++i)
            {
                if( i == 0)
                //첫 인덱스인 경우
                {
                    if(flowerbed[i] == 0 && flowerbed[i+1] == 0)
                    {
                        flowerbed[i] = 1;
                        ++AcceptCount;
                    }
                        
                }
                else if(i == (flowerbed.Length-1))
                {
                //마지막 인덱스인 경우
                    if(flowerbed[i] == 0 && flowerbed[i-1] == 0)
                    {
                        flowerbed[i] = 1;
                        ++AcceptCount;
                    }
                }
                else
                {
                // 중간 인덱스인 경우
                    if(flowerbed[i] == 0 && flowerbed[i+1] == 0 && flowerbed[i-1] == 0)
                    {
                        flowerbed[i] = 1;
                        ++AcceptCount;
                    }
                        
                }
            }
        }

        if(AcceptCount >= n)
            return true;
        
        return false;
    }
}

 

[결과]

[후기]

돌려막기식의 지저분한 코드를 작성했다는 점에서 다시 좌절스럽긴하다...

또, 문제 이해를 할 수 없던 비루한 영어실력에도 좌절스럽기도하고..

 

arraybound 에러때문에 저렇게 예외처리를 할 수 밖에없었는데, 더 나은 코드 아이디어를 보기위해 accepted 뜬 이후에 솔루션쪽을 봤는데, 다른 여러 프로그래머들도 앞뒤 인덱스 체크하고 나처럼 000으로 체크된 인덱스에 1 을 박아넣는 가정법형식의 코드를 작성하고 있었다. 진짜 노답이다 싶을정도의 지저분한 코드를 작성했다고 생각했는데, 다른사람들도 비슷한 생각을 가지고 접근했다니 다행스루..

 

다음 문제나 읽어보고 생각이나 방법론이나 생각해야지.

 

반응형
Comments