美文网首页
IOS 算法(基础篇) -----种花问题

IOS 算法(基础篇) -----种花问题

作者: ShawnAlex | 来源:发表于2021-03-26 16:20 被阅读0次

假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。给你一个整数数组 flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false。
1. 1 <= flowerbed.length <= 2 * 104
2. flowerbed[i] 为 0 或 1
3. flowerbed 中不存在相邻的两朵花
4. 0 <= n <= flowerbed.length

例子:

输入:flowerbed = [1,0,0,0,1], n = 1
输出:true

输入:flowerbed = [1,0,0,0,1], n = 2
输出:false

输入:flowerbed = [0], n = 1
输出:true

输入:flowerbed = [1, 0], n = 1
输出:false

解题思路:

遍历法

通过首尾补0方式, 减少遍历前判断

一次遍历如果遇到是 0, 0, 0 就变为 0, 1, 0

代码:

未翻译版
    func canPlaceFlowers(_ flowerbed: [Int], _ n: Int) -> Bool {

        var temp = flowerbed, result = 0
        temp.append(0)
        temp.insert(0, at: 0)

        for i in 1..<temp.count - 1 {
            if temp[i-1] == 0 && temp[i] == 0 && temp[i+1] == 0 {
                temp[i] = 1
                result += 1
            }
        }
        
        return result >= n
    
    }
翻译版
    func canPlaceFlowers(_ flowerbed: [Int], _ n: Int) -> Bool {

        // 定义容器数组为flowerbed, 变化次数result
        var temp = flowerbed, result = 0

        // 首尾插入0
        temp.append(0)
        temp.insert(0, at: 0)

        // 遍历
        for i in 1..<temp.count - 1 {
 
            // 如果遇到三个0, 变为0, 1, 0, 变化次数 +1
            if temp[i-1] == 0 && temp[i] == 0 && temp[i+1] == 0 {
                temp[i] = 1
                result += 1
            }
        }
        
        // 返回结果 大于等于n true; 小于等于n false 
        return result >= n
    
    }

题目来源:力扣(LeetCode) 感谢力扣爸爸 :)
IOS 算法合集地址

相关文章

网友评论

      本文标题:IOS 算法(基础篇) -----种花问题

      本文链接:https://www.haomeiwen.com/subject/boojhltx.html