标签:tin some ++ 规则 repr OLE als example array
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 0 and 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.
给定一个花坛(表示为包含0和1的数组,其中0表示空,1表示不为空)和数字n,如果可以在其中种植n个新花而不违反无邻花规则则返回。
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1 Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2 Output: False
Note:
1 class Solution { 2 public boolean canPlaceFlowers(int[] flowerbed, int n) { 3 int count=0; 4 for(int i=0;i<flowerbed.length && count<n;i++){ 5 if(flowerbed[i]==0){ 6 int next=(i==flowerbed.length-1)? 0:flowerbed[i + 1]; 7 int pre=(i==0) ? 0:flowerbed[i-1]; 8 if(next==0 && pre==0){ 9 flowerbed[i]=1; 10 count++; 11 } 12 } 13 } 14 return count==n; 15 } 16 }
贪心算法
数组的前一项和后一项都添0
这样对于每个i,如果它的前后都为0,就置为1,且计数+1
标签:tin some ++ 规则 repr OLE als example array
原文地址:https://www.cnblogs.com/chanaichao/p/9651606.html