90.种花问题

一、题目描述

假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。

给你一个整数数组 flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false。

在这里插入图片描述

二、解题思路

输入的数组中不能有相邻的1,假设有这么个花坛,n=2;
在这里插入图片描述

使用一个指针,从开始遍历,第一个位置有树,那么直接跳到第三个位置,此时要先判断第三个位置的下一个位置是不是有树,发现没有,此时再第三个位置种上树,n-1=1.
在这里插入图片描述

此时继续向后遍历,跳到第五个位置,发现有树,那么此时就不能再种了,但是还有剩下的没有种的树,所以最后要返回false,这是第一种情况。

第二种情况,假设花坛如下所示,此时要想种花,必须满足:最后一个位置没有种树,或者如果花坛足够长,当前ii+1的位置都没有种树,那么可以继续种,此时:
在这里插入图片描述

第三种情况,假如i在第五个位置(上图的那个位置),并且花坛足够长,但是呢此时i+1的位置第六个位置是有树的,那么只能在i+3的位置进行种树:
在这里插入图片描述

三、代码演示

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        //使用一个指针用来遍历花坛的每个位置
        int i = 0;

        //当花坛遍历完或者花种完了停止循环
        while (i< flowerbed.length && n>0){
            if (flowerbed[i] == 1){
                //如果当前花坛已经种花,那么至少需要到i+2的地方种花
                i += 2;
                //第二种情况
            }else if (i== flowerbed.length-1 || flowerbed[i+1]==0){
                /**
                 * i没有种花,且是最后一个花坛
                 * i和i+1的位置都没有种花
                 * 那么i处肯定可以种植一种花
                 */
                n--;
                i += 2;
            }else{
                //i处没有种花,但是i+1处种花了,这个时候至少需要到i+3的地方才能种花
                i += 3;
            }
        }
        return n<=0;
    }
}
#!/usr/bin/python # -*- coding:utf-8 -*- import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler, PolynomialFeatures from sklearn.pipeline import Pipeline import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as mpatches if __name__ == "__main__": path = './iris.data' # 数据文件路径 data = pd.read_csv(path, header=None) data[4] = pd.Categorical(data[4]).codes x, y = np.split(data.values, (4,), axis=1) # print 'x = \n', x # print 'y = \n', y # 仅使用前两列特征 x = x[:, :2] lr = Pipeline([('sc', StandardScaler()), ('poly', PolynomialFeatures(degree=10)), ('clf', LogisticRegression()) ]) lr.fit(x, y.ravel()) y_hat = lr.predict(x) y_hat_prob = lr.predict_proba(x) np.set_printoptions(suppress=True) print('y_hat = \n', y_hat) print('y_hat_prob = \n', y_hat_prob) print('准确度:%.2f%%' % (100*np.mean(y_hat == y.ravel()))) # 画图 N, M = 200, 200 # 横纵各采样多少个值 x1_min, x1_max = x[:, 0].min(), x[:, 0].max() # 第0列的范围 x2_min, x2_max = x[:, 1].min(), x[:, 1].max() # 第1列的范围 t1 = np.linspace(x1_min, x1_max, N) t2 = np.linspace(x2_min, x2_max, M) x1, x2 = np.meshgrid(t1, t2) # 生成网格采样点 x_test = np.stack((x1.flat, x2.flat), axis=1) # 测试点 # # 无意义,只是为了凑外两个维度 # x3 = np.ones(x1.size) * np.average(x[:, 2]) # x4 = np.ones(x1.size) * np.average(x[:, 3]) # x_test = np.stack((x1.flat, x2.flat, x3, x4), axis=1) # 测试点 mpl.rcParams['font.sans-serif'] = ['simHei'] mpl.rcParams['axes.unicode_minus'] = False cm_light = mpl.colors.ListedColormap(['#77E0A0', '#FF8080', '#A0A0FF']) cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b']) y_hat = lr.predict(x_test) # 预测值 y_hat = y_hat.reshape(x1.shape) # 使之与输入的形状同 plt.figure(facecolor='w') plt.pcolormesh(x1, x2, y_hat, cmap=cm_light) # 预测值的显示 plt.scatter(x[:, 0], x[:, 1], c=y.flat, edgecolors='k', s=50, cmap=cm_dark) # 样本的显示 plt.xlabel(u'萼长度', fontsize=14) plt.ylabel(u'萼宽度', fontsize=14) plt.xlim(x1_min, x1_max) plt.ylim(x2_min, x2_max) plt.grid() patchs = [mpatches.Patch(color='#77E0A0', label='Iris-setosa'), mpatches.Patch(color='#FF8080', label='Iris-versicolor'), mpatches.Patch(color='#A0A0FF', label='Iris-virginica')] plt.legend(handles=patchs, fancybox=True, framealpha=0.8) plt.title(u'鸢尾Logistic回归分类效果 - 标准化', fontsize=17) plt.show()
最新发布
03-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值