贪心算法解种植花朵问题

贪心算法解种植花朵问题

题目:Input: flowerbed = [1,0,0,0,1], n = 1 Output: True

题目解释:1代表已经有花种下,0表示还没有花种下,两朵花之间至少需要1个间隔,求解能否种花。
解题思路:两朵花之间至少有一个间隔,则当前位置的前一个位置和后一个位置都为0
pre=i==0?0:flowerbed[i-1];
next = i == flowerbed.length-1?0:flowerbed[i+1]
;

全部代码如下:

package test;

public class Flowers {

	public static void main(String[] args) {
		int flowerbed[] = {1,0,0,0,1};
		System.out.println(canPlaceFlowers(flowerbed, 1));
	}
	
	public static boolean canPlaceFlowers(int[] flowerbed, int n) {
	   int cnt = 0;
	   for(int i=0;i<flowerbed.length;i++){
		   if(flowerbed[i]==1){
			   continue;
		   }
		   int pre = i == 0 ? 0: flowerbed[i-1];
		   int next = i == flowerbed.length-1 ? 0: flowerbed[i+1];
		   if(pre == 0 && next == 0){
			   cnt++;
			   flowerbed[i] = 1;
		   }
	   }	   
	   System.out.println("还能种"+cnt+"朵花 ");
	   return cnt>=n;	   
	}
}

发布了29 篇原创文章 · 获赞 8 · 访问量 921

猜你喜欢

转载自blog.csdn.net/qq_38650808/article/details/98618061
今日推荐