diff --git a/solution/0600-0699/0605.Can Place Flowers/README.md b/solution/0600-0699/0605.Can Place Flowers/README.md index c4e5a80566801..a9be6a2602e8b 100644 --- a/solution/0600-0699/0605.Can Place Flowers/README.md +++ b/solution/0600-0699/0605.Can Place Flowers/README.md @@ -43,6 +43,10 @@ **方法一:贪心** +我们直接遍历数组 $flowerbed$,对于每个位置 $i$,如果 $flowerbed[i]=0$,并且其左右相邻位置都为 $0$,则我们可以在该位置种花,否则不能。最后我们统计可以种下的花的数量,如果其不小于 $n$,则返回 $true$,否则返回 $false$。 + +时间复杂度 $O(n)$,其中 $n$ 是数组 $flowerbed$ 的长度。我们只需要遍历数组一次。空间复杂度 $O(1)$。 + ### **Python3** @@ -123,6 +127,23 @@ func canPlaceFlowers(flowerbed []int, n int) bool { } ``` +### **TypeScript** + +```ts +function canPlaceFlowers(flowerbed: number[], n: number): boolean { + const m = flowerbed.length; + for (let i = 0; i < m; ++i) { + const l = i === 0 ? 0 : flowerbed[i - 1]; + const r = i === m - 1 ? 0 : flowerbed[i + 1]; + if (l + flowerbed[i] + r === 0) { + flowerbed[i] = 1; + --n; + } + } + return n <= 0; +} +``` + ### **PHP** ```php diff --git a/solution/0600-0699/0605.Can Place Flowers/README_EN.md b/solution/0600-0699/0605.Can Place Flowers/README_EN.md index 7f61d4fa89981..1a44d5a13982e 100644 --- a/solution/0600-0699/0605.Can Place Flowers/README_EN.md +++ b/solution/0600-0699/0605.Can Place Flowers/README_EN.md @@ -28,6 +28,12 @@ ## Solutions +**Solution 1: Greedy** + +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$. + +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)$. + ### **Python3** @@ -104,6 +110,23 @@ func canPlaceFlowers(flowerbed []int, n int) bool { } ``` +### **TypeScript** + +```ts +function canPlaceFlowers(flowerbed: number[], n: number): boolean { + const m = flowerbed.length; + for (let i = 0; i < m; ++i) { + const l = i === 0 ? 0 : flowerbed[i - 1]; + const r = i === m - 1 ? 0 : flowerbed[i + 1]; + if (l + flowerbed[i] + r === 0) { + flowerbed[i] = 1; + --n; + } + } + return n <= 0; +} +``` + ### **PHP** ```php diff --git a/solution/0600-0699/0605.Can Place Flowers/Solution.ts b/solution/0600-0699/0605.Can Place Flowers/Solution.ts new file mode 100644 index 0000000000000..ea63ee4bf8fd2 --- /dev/null +++ b/solution/0600-0699/0605.Can Place Flowers/Solution.ts @@ -0,0 +1,12 @@ +function canPlaceFlowers(flowerbed: number[], n: number): boolean { + const m = flowerbed.length; + for (let i = 0; i < m; ++i) { + const l = i === 0 ? 0 : flowerbed[i - 1]; + const r = i === m - 1 ? 0 : flowerbed[i + 1]; + if (l + flowerbed[i] + r === 0) { + flowerbed[i] = 1; + --n; + } + } + return n <= 0; +}