683. K Empty Slots

问题描述
There is a garden with N slots. In each slot, there is a flower. The N flowers will bloom one by one in N days. In each day, there will be exactly one flower blooming and it will be in the status of blooming since then.
Given an array flowers consists of number from 1 to N. Each number in the array represents the place where the flower will open in that day.
For example, flowers[i] = x means that the unique flower that blooms at day i will be at position x, where i and x will be in the range from 1 to N.
Also given an integer k, you need to output in which day there exists two flowers in the status of blooming, and also the number of flowers between them is k and these flowers are not blooming.
If there isn’t such day, output -1.
Example1:
这里写图片描述
Example2:
这里写图片描述
Note: The given array will be in the range [1, 20000].

解题思路
该问题是花园中有N个槽,每次在槽中种一朵花。给定种花的顺序flowers,flowers[i] = x表示第i天,在第x个槽种下一朵花。另外给定数字k,求flowers中是否存在某一天,满足相隔k距离的两个端点恰好各有一朵花,而这两朵花之间的k个槽都没有花。我们可以用一个数组k来存储种花的信息数组的下标表示在第几个槽,而数组的元素值表示这个槽种花的日期,首先可以遍历flowers将所有花种下去,信息存储在day[]中,定义好两个相距k的点在数组中移动,然后遍历day[]寻找满足条件的结果。

代码展示

#include<iostream>
#include<stdlib.h>
#include<vector>
#include<math.h>

using namespace std;

class Solution {
public:
    int kEmptySlots(vector<int>& flowers, int k) {
        int n = flowers.size();
        int day[n];
        for(int i=0;i<n;i++){
            day[flowers[i]-1] = i+1;
        }
        int L=0, R= k+1, res=20000; 
        for(int i=0;R<n;i++){
            if(day[i] < day[L] || day[i] <= day[R]){   
                if(i == R)  res = min(res, max(day[L], day[R])); 
                L = i;
                R = k + 1 + i;
            }
        } 
        return (res == 20000)?-1:res;
    }
}; 

int main(){
    int n, a;
    vector<int> flowers;
    cout<<"请输入flowers的大小:";
    cin>>n;
    for(int i = 0;i<n;i++){
        cin>>a;
        flowers.push_back(a);
    }
    int k;
    cout<<"请输入k值:"; 
    cin>>k;
    Solution solution;
    int result=solution.kEmptySlots(flowers, k);

     cout<<result<<endl;
}

运行结果展示
这里写图片描述
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值