使用bucket
class Solution: def kEmptySlots(self, bulbs: List[int], K: int) -> int: size = len(bulbs) // (K + 1) + 1 maxBuckets = [None] * size minBuckets = [None] * size for i in range(len(bulbs)): bulb = bulbs[i] bucket = bulb // (K + 1) if not maxBuckets[bucket] or maxBuckets[bucket] < bulb: maxBuckets[bucket] = bulb if not minBuckets[bucket] or minBuckets[bucket] > bulb: minBuckets[bucket] = bulb if bucket != 0 and maxBuckets[bucket - 1]: if minBuckets[bucket] - maxBuckets[bucket - 1] == K + 1: return i + 1 if bucket != size - 1 and minBuckets[bucket + 1]: if minBuckets[bucket + 1] - maxBuckets[bucket] == K + 1: return i + 1 return -1
使用Java的TreeSet
class Solution { public int kEmptySlots(int[] bulbs, int K) { TreeSet<Integer> set = new TreeSet(); for (int i = 0; i < bulbs.length; i++) { Integer higher = set.higher(bulbs[i]); if (higher != null && higher - bulbs[i] == K + 1) return i + 1; Integer lower = set.lower(bulbs[i]); if (lower != null && bulbs[i] - lower == K + 1) return i + 1; set.add(bulbs[i]); } return -1; } }