[leetcode]K Empty Slots
作者:互联网
使用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; } }
标签:bulbs,return,int,bucket,maxBuckets,Slots,minBuckets,leetcode,Empty 来源: https://www.cnblogs.com/lautsie/p/12242649.html