LV. Easy 😎
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
문제
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
Constraints:
- 1 <= flowerbed.length <= 2 * 10^4
- flowerbed[i] is 0 or 1.
- There are no two adjacent flowers in flowerbed.
- 0 <= n <= flowerbed.length
문제 해결법
앞에서부터 배열을 확인하면서 i - 1, i, i + 1이 0이면 i를 0으로 바꿔주고, n--를 해줬다.
배열이 끝나기 전에 n이 0이 되면 true를 리턴!
배열의 사이즈가 1이거나 n이 0인 경우는 특별 케이스로 위에 빼줘서 계산해줬다.
해결 코드
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int length = flowerbed.size();
if (n == 0 || (length == 1 && flowerbed[0] == 0 && n <= 1))
return 1;
else if (length == 1)
return 0;
for (int i = 0; i < length; ++i) {
cout << i << endl;
if (i == 0 && flowerbed[i] == 0 && flowerbed[i + 1] == 0) {
flowerbed[i] = 1;
i++;
n--;
if (n == 0)
return 1;
}
else if (i == 0)
continue;
else if (i == length - 1 && flowerbed[i - 1] == 0 && flowerbed[i] == 0) {
flowerbed[i] = 1;
i++;
n--;
if (n == 0)
return 1;
}
else if (flowerbed[i - 1] == 0 && flowerbed[i] == 0 && flowerbed[i + 1] == 0){
flowerbed[i] = 1;
i++;
n--;
if (n == 0)
return 1;
}
}
return n == 0;
}
};
'Computer Science > 알고리즘' 카테고리의 다른 글
leetcode 142) Linked List Cycle II (0) | 2022.01.19 |
---|---|
leetcode 290) Word Pattern (0) | 2022.01.18 |
leetcode 1345) Jump Game IV (0) | 2022.01.18 |
leetcode 8) String to Integer (atoi) (0) | 2022.01.14 |
leetcode 452) Minimum Number of Arrows to Burst Balloons (0) | 2022.01.14 |
댓글