LeetCode 605. Can Place Flowers 自己的解法
来源:互联网 发布:量化投资python教材 编辑:程序博客网 时间:2024/05/16 08:29
题目
原文大意:假定你要种花,但是相邻良两朵花之间至少有一个间隔。对应到数组中就是:0代表空格,1代表花。
给定这样的01数组,再给定数字n,判断这个数组中是否还能种下n多花,即能否插入n个1。
分析
敲完代码之后觉得自己虽然提交能Accepted,但是算法还是稍显冗余。我的大致思路是,得到这个数组所有为1的位置,然后根据相邻两个1之间的间隔来判断能插入多少个0,求出他们的和,如果n大于这个和,那么就不能插入,否则就可以插入。
例如:
100011000001
第一个1和第二个1之间相隔3,通过公式2*m+1 < t得出m,类似的求出所有这样的结果
需要注意的是,如果开头不是1或者结尾不是1,那么就需要做特殊处理。
代码
class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { List<Integer> list=new ArrayList<>(); for(int i=0;i<flowerbed.length;i++){ //找到所有1的位置,存进list if(flowerbed[i]==1){ list.add(i); } } if(list.isEmpty()){ //list为空时候的处理 return (flowerbed.length+1)/2>=n?true:false; } //开头不是1的特殊处理 int count=list.get(0)<2?0:list.get(0)/2; //剩下情况的处理 for(int i=1; i<list.size();i++){ //这里为什么是减2不是减1,因为两个位置之间的间隔是位置之差减1,再减1是公式的1 count+=(list.get(i)-list.get(i-1)-2)/2; } //结尾不是1的特殊处理 int sub=flowerbed.length-1-list.get(list.size()-1); count+=sub<2?0:sub/2; if(count>=n) return true; return false; }}
阅读全文
0 0
- LeetCode 605. Can Place Flowers 自己的解法
- [leetcode]605. Can Place Flowers
- [LeetCode]605. Can Place Flowers
- [LeetCode]605. Can Place Flowers
- LeetCode 605.Can Place Flowers
- [leetcode]: 605. Can Place Flowers
- [LeetCode] 605. Can Place Flowers
- LeetCode: 605. Can Place Flowers
- leetcode 605. Can Place Flowers
- LeetCode 605. Can Place Flowers
- LeetCode 605. Can Place Flowers
- LeetCode-605. Can Place Flowers
- leetcode 605. Can Place Flowers
- leetcode[Can Place Flowers]
- leetcode-Can Place Flowers
- leetCode-Can Place Flowers
- LeetCode Can Place Flowers
- 605. Can Place Flowers
- 什么是分类?
- 简单搞定hdfs读写流程
- 后缀自动机习题集与归纳
- 2017多校第一场 Add More Zero(hdu6033)
- CentOS 6.5系统安装配置LAMP(Apache+PHP5+MySQL)服务器环境
- LeetCode 605. Can Place Flowers 自己的解法
- Redis 4.0.1集群搭建
- 【深入剖析Tomcat笔记】第六篇 Tomcat Lifecycle
- 南阳oj36 最长公共子序列 动态规划
- ajax基础
- Oracle基础(1)——用户
- foreach模板
- 全栈工程师之路-中级篇之小程序开发-第三章第四节点击查看大图,保存壁纸
- mysql的四种连接方式