170.Can Place Flowers

题目:

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. The input array won't violate no-adjacent-flowers rule.输入数组不会违反no-adjacent-flowers规则。
  2. The input array size is in the range of [1, 20000].输入数组大小在[1,20000]范围内。
  3. n is a non-negative integer which won't exceed the input array size.n是一个非负整数,不会超过输入数组大小。

解答:

 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

扫描二维码关注公众号,回复: 3210743 查看本文章

这样对于每个i,如果它的前后都为0,就置为1,且计数+1

猜你喜欢

转载自www.cnblogs.com/chanaichao/p/9651606.html