Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 그래프 자바
- leetcode 1721
- 자바 리트코드
- 리트코드 자바
- DP
- 백준 16935
- 카카오
- Java
- dfs
- 스프링 에러
- 코테
- 코딩테스트
- 분할정복
- 백준
- 자바
- 인텔리제이 에러
- java 프로그래머스
- 자바 5464
- 리트코드
- java leetcode
- 백준 18222
- 리트코드 1557
- 스택
- BFS
- daily challenge
- leetcode
- 파이썬
- 프로그래머스 java
- 구현
- 프로그래머스
Archives
- Today
- Total
레벨업 일지
[Java] leetcode 605. Can Place Flowers 본문
문제
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
0 1 로 이루어진 꽃밭이 있는데, 꽃의 개수 n이 주어지면 심을 수 있는지 없는지 리턴하는 문제
풀이
이 풀이는 0, 1 로 이루어진 배열을 보니 0의 개수를 카운팅하면 풀수있을까? 에서 출발한다.
풀이 알고리즘은 다음과 같다.
- 숫자 1 사이의 0의 개수 n 을 카운팅
- 선형 탐색을 하여 숫자 1일때 (n-1)/2 를 answer 에 누적합 후 n = 0 초기화
- 숫자 0 으로 시작하거나 끝나면 n +=1
- count + (zeroCnt-1) / 2 >= n 을 리턴한다.
단순히 1 과 1 사이의 0 의 개수를 카운팅한다. ( 예외는 뒤에 설명 )
0의 개수 | 형태 | 1이 들어갈수 있는 max값 |
0 | 1 1 | 0 |
1 | 1 0 1 | 0 |
2 | 1 0 0 1 | 0 |
3 | 1 0 0 0 1 | 1 |
4 | 1 0 0 0 0 1 | 1 |
5 | 1 0 0 0 0 0 1 | 2 |
6 | 1 0 0 0 0 0 0 1 | 2 |
7 | 1 0 0 0 0 0 0 0 1 | 3 |
8 | 1 0 0 0 0 0 0 0 0 1 | 3 |
위의 표를 보면 1이 들어갈수 있는 max값이 규칙을 띄는 것을 볼수 있다.
여기서 알고리즘 2를 연역적 도출하였다.
양 끝이 0 으로 이루어진 예외처리는 알고리즘 3, 4 의 방법으로 예외처리하였다.
코드
자바
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
if(flowerbed[0] ==0 && flowerbed.length ==1 )return true;
int count= 0;
int zeroCnt = 0;
for(int i = 0 ;i < flowerbed.length ;i++){
//count zero between 1
if(flowerbed[i] == 0){
if(i == 0 || i == flowerbed.length-1)//put 1 only if each side.
zeroCnt++;
zeroCnt++;
}else{
count += (zeroCnt-1)/2;
zeroCnt = 0;
}
}
return count + (zeroCnt-1)/2 >= n;
}
}
'알고리즘 > leetcode' 카테고리의 다른 글
[Java] leetcode 1319. Number of Operations to Make Network Connected (2) | 2023.03.24 |
---|---|
[Java] leetcode 2492. Minimum Score of a Path Between Two Cities (0) | 2023.03.23 |
[Java] leetcode 1472. Design Browser History (0) | 2023.03.18 |
[Java] leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal (2) | 2023.03.17 |
[Java] leetcode 997. Find the Town Judge (0) | 2023.02.23 |
Comments