您的位置:首页 > 其它

[Leetcode] 683. K Empty Slots 解题报告

2018-02-02 10:39 176 查看
题目

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.

Example 1:

Input:
flowers: [1,3,2]
k: 1
Output: 2
Explanation: In the second day, the first and the third flower have become blooming.


Example 2:

Input:
flowers: [1,2,3]
k: 1
Output: -1


Note:

The given array will be in the range [1, 20000].
思路

本题目描述中的数组索引是从1开始的,这和程序猿们通常让索引从0开始的习惯有所出入。为了统一,我们在描述中对于索引还是从1开始,只是在实现中稍加改变。

思路是:我们额外定义一个数组days,用来表示每朵花的开花时间,例如days[i] = y表示在位置i上的花的开花时间是第y天。那么问题就转化为:给定days数组之后,找出一个子区间[left, left + 1, ...left + k - 1, right),满足对于任意的i = left + 1,...left + k - 1,满足days[left] < days[i] && days[right] < days[i]。如果找到了,就返回true,否则就返回false。

代码

class Solution {
public:
int kEmptySlots(vector<int>& flowers, int k) {
vector<int> days(flowers.size());
for(int i = 0; i < flowers.size(); ++i) {
days[flowers[i] - 1] = i + 1;
}
int left = 0, right = k + 1, res = INT_MAX;
for(int i = 0; right < days.size(); ++i) {
if(days[i] < days[left] || days[i] <= days[right]) {
if(i == right) {
res = min(res, max(days[left], days[right])); // we get a valid subarray
}
left = i, right = k + 1 + i;
}
}
retur
a920
n (res == INT_MAX)? -1 : res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: