C++ solution using a set


  • 0
    G
    class Solution {
    public:
        int kEmptySlots(vector<int>& flowers, int k) {
            set<int> tree;
            tree.insert(flowers[0]);
            
            for(int i = 1; i < flowers.size(); ++i){
                auto res = tree.lower_bound(flowers[i]);
                
                res = prev(res);
                
                if(res != tree.end() && flowers[i] - *res == k + 1){
                    return i + 1;
                }
                
                auto res2 = tree.upper_bound(flowers[i]);
                
                if(res2 != tree.end() && *res2 - flowers[i] == k + 1){
                    return i + 1;
                }
                
                tree.insert(flowers[i]);
            }
            
            return -1;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.