首页 分享 leetcode 605 种花问题 (c++和python)

leetcode 605 种花问题 (c++和python)

来源:花匠小妙招 时间:2024-12-17 09:13

目录

题目

思路

c++

python 

题目

假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。

给你一个整数数组  flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false。

示例 1:

输入:flowerbed = [1,0,0,0,1], n = 1
输出:true
示例 2:

输入:flowerbed = [1,0,0,0,1], n = 2
输出:false
 

提示:

1 <= flowerbed.length <= 2 * 104
flowerbed[i] 为 0 或 1
flowerbed 中不存在相邻的两朵花
0 <= n <= flowerbed.length

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/can-place-flowers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

贪心算法,局部最优解也是全局最优解,局部三种情况下,可以种花。

(1)队头00型,队头种上;

(2)队尾00型,队尾种上;

(3)队内000型,队内种上;

再考虑下特例flowerbed=[0], n = 1,即可。

c++

执行用时:16 ms, 在所有 C++ 提交中击败了59.54%的用户

内存消耗:19.7 MB, 在所有 C++ 提交中击败了82.07%的用户

class Solution {

public:

bool canPlaceFlowers(vector<int>& flowerbed, int n) {

int n_len = flowerbed.size();

if (n_len == 1 && flowerbed[0] == 0 && n == 1) return true;

if (n_len >= 2 && flowerbed[0] == 0 && flowerbed[1] == 0)

{

flowerbed[0] = 1;

n--;

}

if (n_len >= 2 && flowerbed[n_len-2] == 0 && flowerbed[n_len-1] == 0)

{

flowerbed[n_len-1] = 1;

n--;

}

for (int i = 1; i < n_len-1; i++)

{

if (flowerbed[i-1] == 0 && flowerbed[i] == 0 && flowerbed[i+1] == 0)

{

flowerbed[i] = 1;

n--;

}

}

if (n <= 0) return true;

else return false;

}

};

python 

执行用时:24 ms, 在所有 Python 提交中击败了91.35%的用户

内存消耗:13.6 MB, 在所有 Python 提交中击败了50.00%的用户

class Solution(object):

def canPlaceFlowers(self, flowerbed, n):

"""

:type flowerbed: List[int]

:type n: int

:rtype: bool

"""

n_len = len(flowerbed)

if n == 0: return True

if n_len == 1 and flowerbed[0] == 0 and n == 1: return True

if n_len >= 2 and flowerbed[0] == 0 and flowerbed[1] == 0:

flowerbed[0] = 1

n -= 1

if n_len >= 2 and flowerbed[n_len-2] == 0 and flowerbed[n_len-1] == 0:

flowerbed[n_len-1] = 1

n -= 1

for i in range(1, n_len-1):

if flowerbed[i-1] == 0 and flowerbed[i] == 0 and flowerbed[i+1] == 0:

flowerbed[i] = 1

n -= 1

else:

continue

if n <= 0:

return True

else:

return False

'

相关知识

GuoSmallGuo23
力扣605 种花问题
【leetcode】种花问题 c++
力扣题目训练:605
力扣 leetcode 605. 种花问题 (python)
SKYNE/python
LeetCode
58. 最后一个单词的长度
【Python】基础
LeetCode 1

网址: leetcode 605 种花问题 (c++和python) https://www.huajiangbk.com/newsview1142324.html

所属分类:花卉
上一篇: “社区花园自治”模式在南京流行起
下一篇: 自家门前的树影响采光,该如何迁移

推荐分享