LintCode 1138: Can Place Flowers (数学规律+双指针)

本文探讨了在遵循不相邻种植规则的情况下,在花坛中能否种植指定数量的新花的问题。通过分析不同场景下花坛的状态,提出了三种有效的算法解决方案:双指针法、逐个检查法和边界填充法,帮助理解并解决此类问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Can Place Flowers
    Suppose you have a long flowerbed in which some of the pots 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
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
Notice
1.The input array won’t violate no-adjacent-flowers rule.
2.The input array size is in the range of [1, 20000].
3.n is a non-negative integer which won’t exceed the input array size.

解法:
我的解法是分析1和0的规律。
101 gap = 1 -> 0 tree
1001 gap = 2 -> 0 tree
10001 gap = 3 -> 1 tree
100001 gap = 4 -> 1 tree
1000001 gap = 5 -> 2 trees
10000001 gap = 6 -> 2 trees
100000001 gap = 7 -> 3 trees
1000000001 gap = 8 - 3 trees
可知两个1中间可种的树数目为 (gap + 1) / 2 - 1。
而gap = p2 - p1 -1。
用双指针p1, p2遍历vector。p2和p1分别记录下新旧1的位置(p2前,p1后)。p2初始化为0,p1初始化为-1。

class Solution {
public:
    /**
     * @param flowerbed: an array
     * @param n: an Integer
     * @return: if n new flowers can be planted in it without violating the no-adjacent-flowers rule
     */
    bool canPlaceFlowers(vector<int> &flowerbed, int n) {
        int len = flowerbed.size();
        if ((len == 0) || (len < n)) return false;
        
        int p1 = -1, p2 = 0;  //p2 is ahead of p1
        while (p2 < len) {
            while(flowerbed[p2] == 0) p2++;
            if (p2 > 0) {
                int gap = p2 - p1 - 1; //gap is the available slots between 1s, such as 1---1
                n -= (gap + 1) / 2 - 1;
                p1 = p2;
            }
            p2++;
        }
        if (n == 0) return true;
        else return false;
    }
};

解法2:九章的解法,不用双指针,直接遍历,但逻辑较复杂。

public class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int count = 0;
        for (int i = 0; i < flowerbed.length; i++) {
            if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0)
            && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
                flowerbed[i] = 1;
                count++;
            }
            if (count >= n) {
                return true;
            }
        }
        return false;
    }
}

解法2:
在原vector的前后各加一个0,就可以利用公式flowerCount += (zeroCount - 1) >> 1;

class Solution {
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
        flowerbed.insert(flowerbed.begin(), 0);
        flowerbed.push_back(0);
        int bedSize = flowerbed.size();
        int zeroCount = 0, flowerCount = 0;
        for (int i = 0; i < bedSize; i++) {
            if (flowerbed[i] == 1) {
                flowerCount += (zeroCount - 1) >> 1;
                zeroCount = 0;
            } else {
                zeroCount++;
           }
        }
        flowerCount += (zeroCount - 1) >> 1;
        return flowerCount >= n;
    }
};
<think>根据用户提供的系统级指令和用户问题,我需要处理以下内容: 用户问题:用户提供了一段形式化建模语言的代码片段(类似Petri网或领域特定语言),询问"place P: INT init 1++3++5; place Monitor: INT;"这些代码应该写在什么地方。 分析:用户提到的代码片段看起来像是某种建模或仿真工具的输入语言,例如CPN Tools(有色Petri网)或类似工具。其中: - "place P: INT init 1++5++3++5;" 定义了一个名为P的库所(place),类型为整数(INT),初始标记(token)为1,3,5(注意:1++3++5可能表示多个标记,但通常用逗号分隔,这里可能是特定语法)。 - "place Monitor: INT;" 定义了一个名为Monitor的库所,类型为整数,没有初始标记。 用户想知道这些代码应该写在什么位置(即应该在哪个文件或工具的哪个部分编写)。 根据我的知识: 1. 这类代码通常出现在Petri网建模工具中,如CPN Tools、Snoopy等。 2. 在CPN Tools中,模型定义通常在一个.cpn文件中,其中包含声明部分(声明颜色集、变量等)和网络结构部分(定义库所、变迁、弧等)。 3. 具体到代码片段,它们属于库所声明,应该写在模型定义文件中,通常在声明库所的部分。 然而,用户提供的引用内容似乎与机器人控制、深度学习模型配置和嵌入式开发有关,与Petri网建模没有直接关系。因此,我将主要依靠自己的知识来回答。 回答结构: 1. 解释代码含义:简要说明这些语句的作用。 2. 指出编写位置:说明在哪种工具或环境中编写,以及具体在文件的哪个部分。 3. 给出一个示例:展示一个简单的模型文件结构,将用户提供的代码放入上下文中。 4. 生成相关问题:根据用户问题,生成3个相关问题。 注意:使用中文回答,并遵循LaTeX格式要求(行内公式用$...$,独立公式用$$...$$)。</think>### 回答 您提供的代码片段 `place P: INT init 1++3++5; place Monitor: INT;` 属于**形式化建模语言**(如高级 Petri 网或领域特定语言 DSL),通常用于描述系统行为(如并发、状态转移)。这些代码应编写在以下两类文件中: --- #### 1. **建模工具的定义文件** - **文件类型**:`.pnml`(Petri Net Markup Language)、`.cpn`(有色 Petri 网文件)或工具专属文件(如 CPN Tools 的 `.cpn` 文件)。 - **位置**:在工具的**声明部分(Declarations Section)**,用于定义库所(Place)及其初始状态。 - **示例文件结构**: ```python // 颜色集定义(可选) color INT = int; // 库所声明(您的代码在此) place P: INT init 1++3++5; // 初始令牌为1,3,5 place Monitor: INT; // 无初始令牌 // 变迁和弧的定义 trans T1 { // 输入/输出弧规则 } ``` - **工具示例**:CPN Tools[^1]、PIPE(Platform Independent Petri Net Editor)或 Snoopy。 --- #### 2. **仿真代码的初始化模块** - **场景**:若使用编程语言(如 Python/C++)实现 Petri 网仿真,代码需写在**模型初始化函数**中。 - **示例(Python)**: ```python class Place: def __init__(self, name, dtype, initial_tokens=None): self.tokens = initial_tokens or [] # 令牌存储 # 初始化库所(对应您的代码) P = Place("P", int, initial_tokens=[1, 3, 5]) Monitor = Place("Monitor", int) ``` --- ### 关键说明 - **语法解析**: - `init 1++3++5` 表示初始令牌(token)为值 1, 3, 5(`++` 可能是分隔符,具体取决于工具)。 - `INT` 定义令牌数据类型(此处为整数)。 - **验证工具**: 建议使用 Petri 网工具(如 [CPN Tools](https://cpntools.org/))直接编辑和验证语法,避免手动编写错误[^2]。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值