[683. K Empty Slots] C++_Two pointer_AC


  • 0
    class Solution {
    public:
    int kEmptySlots(vector<int>& flowers, int k) {
        if(flowers.size() == 1 && k == 0) return 1;
        if(flowers.size() == 1 && k > 0) return -1;
        vector<int> status(flowers.size() + 1, 0);
        status[flowers[0]] = 1;
        status[flowers[1]] = 1;
        if(abs(flowers[1] - flowers[0]) - 1 == k) return 2;
        for(int i = 2; i < flowers.size(); ++i){
            int cur = flowers[i];
            int left = cur - 1;
            int right = cur + 1;
            status[cur] = 1;
            while(left >= 1 && !status[left]){
                if(cur - left - 1 > k) break;
                left--;
            }
            if(left >= 1 && status[left] && cur - left - 1 == k) return i+1;
            
            while(right < status.size() && !status[right]){
                if(right - cur - 1 > k) break;
                right++;
            }
            if(right < flowers.size() && status[right] && right - cur - 1 == k) return i+1;
        }
        return -1;
    }
    

    };


Log in to reply
 

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