605. Can Place Flowers(python+cpp)
题目:
Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.
Given a flowerbed (represented as an array containing 0and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1 Output: True 12
Example2:
Input: flowerbed = [1,0,0,0,1], n = 2 Output: False 12
Note:
The input array won’t violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won’t exceed the input array size.
解释:
贪心算法。
贪心算法
贪心算法不是对所有问题都能得到整体最优解,关键是贪心策略的选择,选择的贪心策略必须具备无后效性,即某个状态以前的过程不会影响以后的状态,只与当前状态有关
可以直接通过修改flowerbed的值来做:遍历花床,如果某个位置为0,我们就看其前面一个和后面一个位置的值,注意处理首位置和末位置的情况(默认首位的前面和末尾的后一位为0),如果pre和next均为0,那么说明当前位置可以放花,n自减1,并且当前位置的后一个位置一定不能放置,i++,最后看n是否小于等于0。
python代码:
class Solution(object): def canPlaceFlowers(self, flowerbed, n): """ :type flowerbed: List[int] :type n: int :rtype: bool """ #解法1: #首末加0是为了便于处理边界 flowerbed.insert(0,0) flowerbed.append(0) #只遍历原始的数据,不考虑后来加上的 i=1 while i<len(flowerbed)-1: if flowerbed[i]==0: if flowerbed[i-1]==0 and flowerbed[i+1]==0: n-=1 #如果当前这个放置了,那么它后面的一个一定不能再放置 i+=1 i+=1 return n<=0
123456789101112131415161718192021c++代码:
class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { flowerbed.insert(flowerbed.begin(),0); flowerbed.push_back(0); int i=1; while (i<flowerbed.size()-1) { if (flowerbed[i]==0 && flowerbed[i-1]==0 &&flowerbed[i+1]==0) { n--; //如果当前这个放置了,那么后面一个不用判断了,因为一定不能放置。 //无需改变flowerbed[i]的值之后再便利紧接着的一个了,白白浪费时间 i++; } i++; } return n<=0; } };
1234567891011121314151617181920总结:
啊,好妹妹的《红豆词》真好听。
相关知识
605. Can Place Flowers
Flowers and Plants Care
10 Flowers That Represent Love And Family: Floral Bonds
1箱の種類の手動作成天然保存花レジンクラフト用ドライフラワー - Buy Natural Preserved Flowers
preserved Flowers Dried Flowers
dried Flowers For Resin Craft Product on Alibaba.com
客厅仿真绿色植物花卉人造花装饰 - Buy Living Room Simulated Green Plants
flowers Artificial
flower Decoration Product on Alibaba.com
FL
Pink Chrysanthemum Flower Meaning, Symbolism & Spiritual Significance
花毛茛自选种子繁殖栽培技术(Ranunculus optional seed propagation and Cultivation Techniques).doc
Dounan International Flower Market & Distribution Center, Kunming
将会种植更多的鲜花来美化城市 的翻译是:More flowers will be planted to beautify the city 中文翻译英文意思,翻译英语
网址: 605. Can Place Flowers(python+cpp) https://www.huajiangbk.com/newsview1786883.html
上一篇: 【每日一题Day178】LC10 |
下一篇: 微信支付, 推送“支付完成事件” |
推荐分享

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