题目描述
假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。
可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给你一个整数数组 flowerbed 表示花坛,由若干 0 和 1 组成,
其中 0 表示没种植花1 表示种植了花。另有一个数 n
能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false 。
解题思路
连续三个为0则中间位置可以种花
花坛一端(开始或结尾)连续两个为0则当前位置可以种花
只有一个位置且为0则可以种花
核心代码
bool Solution::canPlaceFlowers(vector<int>& flowerbed, int n) { int num = 0; for (int i = 0; i < flowerbed.size(); i++) { if (flowerbed[i] == 0 //判断当前位置是否能种花 && (i == 0 || flowerbed[i - 1] == 0) //或逻辑只要前面条件为真不会判断后面条件,故不会越界访问 && (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) { flowerbed[i] = 1; //满足条件,种花 num++; //种花数量加1 i++; //当前位置能种花则相邻位置一定不能种花,跳过相邻位置 }//end if }//end for return num >= n; }完整可运行代码
#include<iostream> using namespace std; #include<vector> #include<sstream> #include<string> class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n); }; void Init(vector<int>& flowerbed,int &n); //初始化vector声明 int main() { vector<int> flowerbed; int n; Solution s; Init(flowerbed,n); //初始化vector if (s.canPlaceFlowers(flowerbed, n)) cout << "true" << endl; else cout << "false" << endl; system("pause"); return 0; } void Init(vector<int>& flowerbed, int& n) { string input; getline(cin, input); stringstream ss(input); //转换为字符流 int temp; while (ss >> temp) { flowerbed.push_back(temp); } cin >> n; } bool Solution::canPlaceFlowers(vector<int>& flowerbed, int n) { int num = 0; for (int i = 0; i < flowerbed.size(); i++) { if (flowerbed[i] == 0 //判断当前位置是否能种花 && (i == 0 || flowerbed[i - 1] == 0)//或逻辑只要前面条件为真不会判断后面条件,故不会越界访问 && (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) { flowerbed[i] = 1; //满足条件,种花 num++; //种花数量加1 i++; //当前位置能种花则相邻位置一定不能种花,跳过相邻位置 }//end if }//end for return num >= n; }补充知识
i == 0 || flowerbed[i - 1] == 0 //或逻辑只要前面条件为真不会判断后面条件,故不会发生越界访问