先用最直白的解法AC:

class Solution {
public:
    bool kLengthApart(vector<int>& nums, int k) {
        int n = nums.size();
        
        for(int i = 0;i < n;i++)
        {
            if(nums[i] == 1)
            {
                int cnt = k;
                for(int j = i+1;j < n;j++)
                {
                    if(nums[j] == 1)
                    {
                        if(cnt > 0)
                            return false;
                        break;
                    }                    
                    if(nums[j] == 0)
                    {
                        cnt--;
                    }
                    i = j;
                }
            }
               
        }
        return true;
    }
};

运行效率:

Runtime: 44 ms, faster than 96.58% of C++ online submissions for Check If All 1's Are at Least Length K Places Away.
Memory Usage: 57.5 MB, less than 72.40% of C++ online submissions for Check If All 1's Are at Least Length K Places Away.

运行效率也还不错,但是代码有点乱,我们优化后的代码如下:

class Solution {
public:
    bool kLengthApart(vector<int>& nums, int k) {
        int n = nums.size();
        
        for(int i = 0;i < n;i++)
        {
            if(nums[i] == 1)
            {
                int cnt = k;
                while(i+1 < n)
                {
                    if(nums[i+1] == 1)
                    {
                        if(cnt > 0) return false;
                        break;
                    }
                    i++;
                    cnt--;
                }
            }
               
        }
        return true;
    }
};

运行效率:

Runtime: 44 ms, faster than 96.58% of C++ online submissions for Check If All 1's Are at Least Length K Places Away.
Memory Usage: 57.6 MB, less than 35.66% of C++ online submissions for Check If All 1's Are at Least Length K Places Away.

看了一眼讨论区的代码,比较简洁易懂:

class Solution {
public:
    bool kLengthApart(vector<int>& nums, int k) {
        int prev = -k-1;
        int n = nums.size();
        for(int i = 0;i < n;i++)
        {
            if(1 == nums[i])
            {
                if(i - prev <= k) 
                    return false;
                else 
                    prev = i;
            }
        }
        return true;
    }
};

运行效率有点拉跨,运行了好多次都比较差,反而没有开始我写的if else代码运行效率高,你说上哪说理去?

Runtime: 60 ms, faster than 37.43% of C++ online submissions for Check If All 1's Are at Least Length K Places Away.
Memory Usage: 57.4 MB, less than 93.03% of C++ online submissions for Check If All 1's Are at Least Length K Places Away.