683 K Empty Slots
683. K Empty Slots
1. Question
There is a garden withN
slots. In each slot, there is a flower. TheN
flowers will bloom one by one inN
days. In each day, there will beexactly
one flower blooming and it will be in the status of blooming since then.
Given an arrayflowers
consists of number from1
toN
. 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 dayi
will be at positionx
, wherei
andx
will be in the range from1
toN
.
Also given an integerk
, you need to output in which day there exists two flowers in the status of blooming, and also the number of flowers between them isk
and these flowers are not blooming.
If there isn't such day, output -1.
Example 1:
Example 2:
Note:
The given array will be in the range [1, 20000].
2. Implementation
(1) Brute Force
对于每个flowers[i],我们都分别检查在它之前的k个位置,在它的之后的k个位置是否有花,如果有的话,它们之间的是否有k个empty slot,如果有的话,就返回天数。注意这里天数是从1开始算的,而数组是以0开始,所以返回i + 1
(2) Binary Search Tree
利用Binary Search Tree的性质,可以找出一个flowers[i]前一个的key和后一个key,如果刚好之间间隔k,则返回天数。这里我们用treeSet来实现binary search tree
3. Time & Space Complexity
Brute Force: 时间复杂度O(nk), n是flowers数组的size,在这到题指的是天数,空间复杂度O(n)
Binary Search Tree: 时间复杂度O(nlogn), 空间复杂度O(n)
Last updated