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;}
运行结果展示
- 683. K Empty Slots
- 683. K Empty Slots
- LWC 51:683. K Empty Slots
- Qt public slots;protected slots;private slots
- empty()
- empty
- empty
- empty
- empty
- Signals & Slots
- Given a non-empty array of integers, return the k most frequent elements.
- Signals and Slots 翻译
- Private implementation slots
- Signals and Slots
- Slots in iPhone
- QT signal / slots 注意事项
- signal—slots 机制
- QT signals and slots
- 在 CentOS7 上安装 MySQL5.7
- python response.text和response.content的区别
- ios_添加按钮与删除按钮
- NOIP2017初赛吐槽
- vue.js学习笔记(七)--插件
- 683. K Empty Slots
- C++ GUI Programming with Qt4 Second Edition 之 Qt简史
- sysu-17C05签到
- 使用CSDN-markdown编辑器
- 基础知识技巧
- 多线程分析讲解 --------转:C# Thread
- 合并单元格技能get
- JPA 对象继承策略
- Hadoop实战(1)_阿里云搭建Hadoop2.x的伪分布式环境