Skip to content

Commit 519ff75

Browse files
authored
feat: add ts solution to lc problem: No.0605 (#1722)
No.0605.Can Place Flowers
1 parent 101906c commit 519ff75

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

solution/0600-0699/0605.Can Place Flowers/README.md

+21
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,10 @@
4343

4444
**方法一:贪心**
4545

46+
我们直接遍历数组 $flowerbed$,对于每个位置 $i$,如果 $flowerbed[i]=0$,并且其左右相邻位置都为 $0$,则我们可以在该位置种花,否则不能。最后我们统计可以种下的花的数量,如果其不小于 $n$,则返回 $true$,否则返回 $false$。
47+
48+
时间复杂度 $O(n)$,其中 $n$ 是数组 $flowerbed$ 的长度。我们只需要遍历数组一次。空间复杂度 $O(1)$。
49+
4650
<!-- tabs:start -->
4751

4852
### **Python3**
@@ -123,6 +127,23 @@ func canPlaceFlowers(flowerbed []int, n int) bool {
123127
}
124128
```
125129

130+
### **TypeScript**
131+
132+
```ts
133+
function canPlaceFlowers(flowerbed: number[], n: number): boolean {
134+
const m = flowerbed.length;
135+
for (let i = 0; i < m; ++i) {
136+
const l = i === 0 ? 0 : flowerbed[i - 1];
137+
const r = i === m - 1 ? 0 : flowerbed[i + 1];
138+
if (l + flowerbed[i] + r === 0) {
139+
flowerbed[i] = 1;
140+
--n;
141+
}
142+
}
143+
return n <= 0;
144+
}
145+
```
146+
126147
### **PHP**
127148

128149
```php

solution/0600-0699/0605.Can Place Flowers/README_EN.md

+23
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@
2828

2929
## Solutions
3030

31+
**Solution 1: Greedy**
32+
33+
We directly traverse the array $flowerbed$. For each position $i$, if $flowerbed[i]=0$ and its adjacent positions on the left and right are also $0$, then we can plant a flower at this position. Otherwise, we cannot. Finally, we count the number of flowers that can be planted. If it is not less than $n$, we return $true$, otherwise we return $false$.
34+
35+
The time complexity is $O(n)$, where $n$ is the length of the array $flowerbed$. We only need to traverse the array once. The space complexity is $O(1)$.
36+
3137
<!-- tabs:start -->
3238

3339
### **Python3**
@@ -104,6 +110,23 @@ func canPlaceFlowers(flowerbed []int, n int) bool {
104110
}
105111
```
106112

113+
### **TypeScript**
114+
115+
```ts
116+
function canPlaceFlowers(flowerbed: number[], n: number): boolean {
117+
const m = flowerbed.length;
118+
for (let i = 0; i < m; ++i) {
119+
const l = i === 0 ? 0 : flowerbed[i - 1];
120+
const r = i === m - 1 ? 0 : flowerbed[i + 1];
121+
if (l + flowerbed[i] + r === 0) {
122+
flowerbed[i] = 1;
123+
--n;
124+
}
125+
}
126+
return n <= 0;
127+
}
128+
```
129+
107130
### **PHP**
108131

109132
```php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
function canPlaceFlowers(flowerbed: number[], n: number): boolean {
2+
const m = flowerbed.length;
3+
for (let i = 0; i < m; ++i) {
4+
const l = i === 0 ? 0 : flowerbed[i - 1];
5+
const r = i === m - 1 ? 0 : flowerbed[i + 1];
6+
if (l + flowerbed[i] + r === 0) {
7+
flowerbed[i] = 1;
8+
--n;
9+
}
10+
}
11+
return n <= 0;
12+
}

0 commit comments

Comments
 (0)