Skip to content

Commit 1284918

Browse files
committed
[Array] Add a solution to Can Place Flowers
1 parent becfc9c commit 1284918

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

Array/CanPlaceFlowers.swift

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/can-place-flowers/
3+
* Primary idea: Greedy algorithm. Place flowers as early as possible.
4+
* Time Complexity: O(n), Space Complexity: O(1)
5+
*
6+
*/
7+
8+
class CanPlaceFlowers {
9+
func canPlaceFlowers(_ flowerbed: [Int], _ n: Int) -> Bool {
10+
var maxFlowersCouldPlant = 0, flowerbed = flowerbed
11+
12+
for i in 0..<flowerbed.count {
13+
guard flowerbed[i] == 0 else {
14+
continue
15+
}
16+
17+
if i < 1 {
18+
if flowerbed.count == 1 || flowerbed[i + 1] != 1 {
19+
flowerbed[i] = 1
20+
maxFlowersCouldPlant += 1
21+
}
22+
} else if i + 1 == flowerbed.count {
23+
if flowerbed.count == 1 || flowerbed[i - 1] != 1 {
24+
flowerbed[i] = 1
25+
maxFlowersCouldPlant += 1
26+
}
27+
} else {
28+
if flowerbed[i - 1] != 1 && flowerbed[i + 1] != 1 {
29+
flowerbed[i] = 1
30+
maxFlowersCouldPlant += 1
31+
}
32+
}
33+
34+
// early exit
35+
if maxFlowersCouldPlant >= n {
36+
return true
37+
}
38+
}
39+
40+
return maxFlowersCouldPlant >= n
41+
}
42+
}

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
![Leetcode](./logo.png?style=centerme)
55

66
## Progress
7-
[Problem Status](#problem-status) shows the latest progress to all 1000+ questions. Currently we have 302 completed solutions. Note: questions with &hearts; mark means that you have to **Subscript to premium membership** of LeetCode to unlock them.
7+
[Problem Status](#problem-status) shows the latest progress to all 1000+ questions. Currently we have 303 completed solutions. Note: questions with &hearts; mark means that you have to **Subscript to premium membership** of LeetCode to unlock them.
88

99
## Contributors
1010

@@ -59,6 +59,7 @@
5959
[Move Zeroes](https://leetcode.com/problems/move-zeroes/)| [Swift](./Array/MoveZeroes.swift)| Easy| O(n)| O(1)|
6060
[Remove Element](https://leetcode.com/problems/remove-element/)| [Swift](./Array/RemoveElement.swift)| Easy| O(n)| O(1)|
6161
[Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/)| [Swift](./Array/StrobogrammaticNumber.swift)| Easy| O(n)| O(1)|
62+
[Can Place Flowers](https://leetcode.com/problems/can-place-flowers/)| [Swift](./Array/CanPlaceFlowers.swift)| Easy| O(n)| O(1)|
6263
[Two Sum](https://leetcode.com/problems/two-sum/)| [Swift](./Array/TwoSum.swift)| Easy| O(n)| O(n)|
6364
[Two Sum Less Than K](https://leetcode.com/problems/two-sum-less-than-k/)| [Swift](./Array/TwoSumLessThanK.swift)| Easy| O(nlogn)| O(n)|
6465
[3Sum](https://leetcode.com/problems/3sum/)| [Swift](./Array/ThreeSum.swift)| Medium| O(n^2)| O(nC3)|

0 commit comments

Comments
 (0)