[LeetCode] 683. K Empty Slots K个空槽

There is a garden with N slots. In each slot, there is a flower. The N flowers will bloom one by one in N days. In each day, there will be exactly one flower blooming and it will be in the status of blooming since then.

Given an array flowers consists of number from 1 to N. 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 day i will be at position x, where i and x will be in the range from 1 to N.

Also given an integer k, you need to output in which day there exists two flowers in the status of blooming, and also the number of flowers between them is k and these flowers are not blooming.

If there isn't such day, output -1.

Example 1:

Input: 
flowers: [1,3,2]
k: 1
Output: 2
Explanation: In the second day, the first and the third flower have become blooming. 

Example 2:

Input: 
flowers: [1,2,3]
k: 1
Output: -1

Note:

  1. The given array will be in the range [1, 20000].

一个有N个空槽的花园里,每个槽里有一棵花,每天有一棵花会开。给了一个数组flowers,flowers[i] = x表示第i天唯一开花的位置x。又给了一个整数k,判断是否正好有两棵开的花中间有k个空槽,如果有,返回当前天数,否则返回-1。

注意:数组是从0开始的,而天数和位置都是从1开始的,所以是第i+1天放的花会在位置x。

解法1:先把flowers数组转换成天数的数组,表示某一花槽是哪一天开花的。取第一个花槽位置left和k+1位置的花槽位置right(也就是取一个k+2区间),然后遍历花槽位置,看有没有比首尾花槽开花更早的(条件是days[i]<left or days[i]<right),如果有则说明在这个区间形成之前有别的花开了,就不能形成这个k距离的区间,则left变成i,right变成i+k+1,验证下一个区间直到right走到最后。如果i走到位置right同时开花时间正好是days[right],就找到了一个区间,更新result(更新方法是先取left, right开花时间在后的也就是时间大的,然后如果有多个区间,则取这个满足开花时间早的,也就是开花时间里小的),这个条件可以和前一个判断写在一起,具体看代码。 T: O(n),S: O(n)

解法2:treemap(内部排序的hashmap)。遍历数组,每次都将花槽编号放进treemap,同时检查到这天为止离此花槽最近的花槽,如果两个花槽编号之间刚好相差k,返回这时的天数。T: O(nlogn),S: O(n)

Java: 1

class Solution {
    public int kEmptySlots(int[] flowers, int k) {
        int[] days = new int[flowers.length];
        for (int i = 0; i < flowers.length; i++) days[flowers[i] - 1] = i + 1;

        int left = 0, right = k + 1, result = Integer.MAX_VALUE;
        for (int i = 0; right < days.length; i++) {
            if (days[i] < days[left] || days[i] <= days[right]) {
                if (i == right)
                    result = Math.min(result, Math.max(days[left], days[right]));
                left = i;
                right = k + 1 + i;
            }
        }

        return (result == Integer.MAX_VALUE) ? -1 : result;
    }
}  

Java: 2

public int kEmptySlots(int[] flowers, int k) {
        int n = flowers.length;
        if (n == 1 && k == 0) return 1;
        TreeSet<Integer> sort = new TreeSet<>();
        for (int i = 0; i < n; ++i) {
            sort.add(flowers[i]);
            Integer min = sort.lower(flowers[i]);
            Integer max = sort.higher(flowers[i]);
            if (min != null && flowers[i] - min == k + 1) return i + 1;
            if (max != null && max - flowers[i] == k + 1) return i + 1;
        }
        return -1;
    }

Python:

class Solution(object):
    def kEmptySlots(self, flowers, k):
        """
        :type flowers: List[int]
        :type k: int
        :rtype: int
        """
        days = [0] * len(flowers)
        for i in xrange(len(flowers)):
            days[flowers[i]-1] = i
        result = float("inf")
        i, left, right = 0, 0, k+1
        while right < len(days):
            if days[i] < days[left] or days[i] <= days[right]:
                if i == right:
                    result = min(result, max(days[left], days[right]))
                left, right = i, k+1+i;
            i += 1
        return -1 if result == float("inf") else result+1

C++:

// Time:  O(n)
// Space: O(n)
class Solution {
public:
    int kEmptySlots(vector<int>& flowers, int k) {
        vector<int> days(flowers.size());
        for (int i = 0; i < flowers.size(); ++i) {
            days[flowers[i] - 1] = i;
        }
        auto result = numeric_limits<int>::max();
        for (int i = 0, left = 0, right = k + 1; right < days.size(); ++i) {
            if (days[i] < days[left] || days[i] <= days[right]) {   
                if (i == right) {
                    result = min(result, max(days[left], days[right])); 
                }
                left = i, right = k + 1 + i;
            }
        }
        return (result == numeric_limits<int>::max()) ? -1 : result + 1;
    }
};  

C++:

class Solution {
public:
    int kEmptySlots(vector<int>& flowers, int k) {
        int res = INT_MAX, left = 0, right = k + 1, n = flowers.size();
        vector<int> days(n, 0);
        for (int i = 0; i < n; ++i) days[flowers[i] - 1] = i + 1;
        for (int i = 0; right < n; ++i) {
            if (days[i] < days[left] || days[i] <= days[right]) {
                if (i == right) res = min(res, max(days[left], days[right]));
                left = i; 
                right = k + 1 + i;
            }
        }
        return (res == INT_MAX) ? -1 : res;
    }
};

C++:

class Solution {
public:
    int kEmptySlots(vector<int>& flowers, int k) {
        set<int> s;
        for (int i = 0; i < flowers.size(); ++i) {
            int cur = flowers[i];
            auto it = s.upper_bound(cur);
            if (it != s.end() && *it - cur == k + 1) {
                return i + 1;
            }
            it = s.lower_bound(cur);
            if (it != s.begin() && cur - *(--it) == k + 1) {
                return i + 1;
            }
            s.insert(cur);
        }
        return -1;
    }
}; 

C++: Bucket

class Solution {
public:
    int kEmptySlots(vector<int>& flowers, int k) {
        int n = flowers.size();
        if (n == 0 || k >= n) return -1;
        ++k;
        int bs = (n + k - 1) / k;
        vector<int> lows(bs, INT_MAX);
        vector<int> highs(bs, INT_MIN);
        for (int i = 0; i < n; ++i) {
            int x = flowers[i];
            int p = x / k;
            if (x < lows[p]) {
                lows[p] = x;
                if (p > 0 && highs[p - 1] == x - k) return i + 1;
            } 
            if (x > highs[p]) {
                highs[p] = x;
                if (p < bs - 1 && lows[p + 1] == x + k) return i + 1;
            }            
        }
        
        return -1;
    }
};

C++: BST

class Solution {
public:
    int kEmptySlots(vector<int>& flowers, int k) {
        int n = flowers.size();
        if (n == 0 || k >= n) return -1;        
        set<int> xs;        
        for (int i = 0; i < n; ++i) {
            int x = flowers[i];
            auto r = xs.insert(x).first;
            auto l = r;
            if (++r != xs.end() && *r == x + k + 1) return i + 1;
            if (l != xs.begin() && *(--l) == x - k - 1) return i + 1;
        }
        
        return -1;
    }
};

    

follow up:

求最后的有k盆连续开花的是哪一天,就是k个连续不空的槽  

 

 

All LeetCode Questions List 题目汇总

posted @ 2018-09-30 07:21  轻风舞动  阅读(738)  评论(0编辑  收藏  举报