leetcode 605 种花问题 (c++和python)
目录
题目
思路
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
上一篇: “社区花园自治”模式在南京流行起 |
下一篇: 自家门前的树影响采光,该如何迁移 |
推荐分享

- 1君子兰什么品种最名贵 十大名 4012
- 2世界上最名贵的10种兰花图片 3364
- 3花圈挽联怎么写? 3286
- 4迷信说家里不能放假花 家里摆 1878
- 5香山红叶什么时候红 1493
- 6花的意思,花的解释,花的拼音 1210
- 7教师节送什么花最合适 1167
- 8勿忘我花图片 1103
- 9橄榄枝的象征意义 1093
- 10洛阳的市花 1039