这两天一直有面试,所以没来得及更新博客,但也有一直保持做题,其实只要养成了一定的习惯,可能哪一天不AC几道题都会觉着少点什么,所以编程能力自然而然也会有很大的提升,今天和大家分享一道比较有意思的题,这里我把它称为种花问题,下面是LeetCode中的题目描述:
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.
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:
- 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.
这道题给了我们一个01数组,其中1表示已经放了花,0表示可以放花的位置,但有个限制条件是不能有相邻的花。那么我们来看如果是一些简单的例子,如果有3个连续的零,000,能放几盆花呢,其实是要取决约左右的位置的,如果是10001,那么只能放1盆,如果左右是边界的花,那么就能放两盆,101,所以如果我们想通过计算连续0的个数,然后直接算出能放花的个数,就必须要对边界进行处理,处理方法是如果首位置是0,那么前面再加上个0,如果末位置是0,就在最后面再加上个0。两个1之间0的个数和可插入的1个数相关,相关关系为sum = (count-1)/2,count为两个1之间局部0的个数,sum则为这一局部可插入1的个数。那么有了这样的解题思路我想代码实现起来也就不是很难了,下面是我的AC代码:
package com.gaoxue.LeetCode;
public class CanPlaceFlowers {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
StringBuilder sb = new StringBuilder();
sb.append(0);
for(int i = 0;i<flowerbed.length;i++){
sb.append(flowerbed[i]);
}
sb.append(0);
String s = sb.toString();
int sum = 0;
int count = 0;
for(int i = 0 ;i < s.length(); i++){
if(s.charAt(i)=='1'){
sum += (count-1)/2;
count = 0;
}else{
count ++;
}
}
sum += (count -1) /2;//最后一组局部如100100
return (n<=sum)?true:false;
}
public static void main(String[] args) {
System.out.println(new CanPlaceFlowers().canPlaceFlowers(new int[] {1,0,0,1,0,0},1));
}
}
相信这段代码理解起来应该比较简单,所以我就不做注释了,代码就是完全按照上述的解题思路完成的,另外呢,这里我跟大家提一下这道题是可以用贪心算法解决的,但是代码实现我还是希望大家都可以自己多思考一下,在后面的博文中我会对这些遗留问题做详细介绍,大家可以先试着自己实现然后再来一块探讨,总之今日事、今日毕,大家可以根据自己情况制定一个合理的学习计划,望大家都可以更上一层楼,一同进步哈~