Google
683 K Empty Slots

1. Question

There is a garden withNslots. In each slot, there is a flower. TheNflowers will bloom one by one inNdays. In each day, there will beexactlyone flower blooming and it will be in the status of blooming since then.
Given an arrayflowersconsists of number from1toN. Each number in the array represents the place where the flower will open in that day.
For example,flowers[i] = xmeans that the unique flower that blooms at dayiwill be at positionx, whereiandxwill be in the range from1toN.
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 iskand these flowers are not blooming.
If there isn't such day, output -1.
Example 1:
1
Input:
2
3
flowers: [1,3,2] k: 1
4
5
Output: 2
6
7
Explanation: In the second day, the first and the third flower have become blooming.
Copied!
Example 2:
1
Input:
2
3
flowers: [1,2,3] k: 1
4
5
Output: -1
Copied!
Note:
  1. 1.
    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
1
class Solution {
2
public int kEmptySlots(int[] flowers, int k) {
3
if (flowers == null || k >= flowers.length) {
4
return -1;
5
}
6
7
int n = flowers.length;
8
int[] slots = new int[n + 1];
9
10
for (int i = 0; i < n; i++) {
11
if (isValid(flowers[i], k, n, slots)) {
12
return i + 1;
13
}
14
}
15
return -1;
16
}
17
18
public boolean isValid(int curSlot, int k, int n, int[] slots) {
19
slots[curSlot] = 1;
20
21
if (curSlot + k + 1 <= n && slots[curSlot + k + 1] == 1) {
22
for (int i = 1; i <= k; i++) {
23
if (slots[curSlot + i] == 1) {
24
return false;
25
}
26
}
27
return true;
28
}
29
30
if (curSlot - k - 1 >= 0 && slots[curSlot - k - 1] == 1) {
31
for (int i = 1; i <= k; i++) {
32
if (slots[curSlot - i] == 1) {
33
return false;
34
}
35
}
36
return true;
37
}
38
39
return false;
40
}
41
}
Copied!
(2) Binary Search Tree
利用Binary Search Tree的性质,可以找出一个flowers[i]前一个的key和后一个key,如果刚好之间间隔k,则返回天数。这里我们用treeSet来实现binary search tree
1
class Solution {
2
public int kEmptySlots(int[] flowers, int k) {
3
if (flowers == null || k >= flowers.length) {
4
return -1;
5
}
6
7
TreeSet<Integer> tree = new TreeSet();
8
int day = 0;
9
10
for (int flower : flowers) {
11
++day;
12
tree.add(flower);
13
14
Integer low = tree.lower(flower);
15
Integer high = tree.higher(flower);
16
17
if ((low != null && low == flower - k - 1)
18
|| (high != null && high == flower + k + 1)) {
19
return day;
20
}
21
}
22
return -1;
23
}
24
}
Copied!

3. Time & Space Complexity

Brute Force: 时间复杂度O(nk), n是flowers数组的size,在这到题指的是天数,空间复杂度O(n)
Binary Search Tree: 时间复杂度O(nlogn), 空间复杂度O(n)