Leetcode 683. K Empty Slots

Problem:

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:

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

Solution:

  谷歌的中频题,好好分析下。这道题的核心还是滑动窗口,不过和传统的滑动窗口不太一样,首先用一个数组days[i] = t记录第i+1个位置的花在第t天开放,就是说数字大的就是花放的时间晚,所以说除了首尾两个数字,中间的k个数字都要大于首尾两个数字即可。若在days[left]和days[right]中发现了某个数比两端小,就说明这个位置的花开得比较早,因此以该处为起点进行窗口滑动,如果到了right的位置仍然没有发现较小值,说明left和right是满足要求的,那么就把days[left]和days[right]中的较大值和结果比较取较小值即可。这道题的难点在于滑动窗口的合理使用,flowers数组的转换其实应该可以想到,滑动窗口的思想是重点。

Code:

 

 1 class Solution {
 2 public:
 3     int kEmptySlots(vector<int>& flowers, int k) {
 4         vector<int> days(flowers.size());
 5         for(int i=0; i<flowers.size();i++)
 6             days[flowers[i] - 1] = i + 1;
 7         int left = 0, right = k + 1, res = INT_MAX;
 8         for(int i = 0; right < days.size(); i++){
 9             if(days[i] < days[left] || days[i] <= days[right]){   
10                 if(i == right)
11                     res = min(res, max(days[left], days[right]));
12                 left = i, right = k + 1 + i;
13             }
14         }
15         return (res == INT_MAX)?-1:res;
16     }
17 };

 

posted on 2019-01-09 15:26  周浩炜  阅读(178)  评论(0编辑  收藏  举报

导航