码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]K Empty Slots

时间:2020-01-30 14:40:54      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:div   def   python   and   使用   none   set   lbs   i++   

使用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;
    }
}

  

[leetcode]K Empty Slots

标签:div   def   python   and   使用   none   set   lbs   i++   

原文地址:https://www.cnblogs.com/lautsie/p/12242649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!