683. K Empty Slots

来源:互联网 发布:色彩分析软件 编辑:程序博客网 时间:2024/06/11 21:23

问题描述
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;}

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

原创粉丝点击