1437. Check If All 1‘s Are at Least Length K Places Away

题目:

Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.

Example 1:

Input: nums = [1,0,0,0,1,0,0,1], k = 2
Output: true
Explanation: Each of the 1s are at least 2 places away from each other.

Example 2:

Input: nums = [1,0,0,1,0,1], k = 2
Output: false
Explanation: The second 1 and third 1 are only one apart from each other.

Example 3:

Input: nums = [1,1,1,1,1], k = 0
Output: true

Example 4:

Input: nums = [0,1,0,1], k = 1
Output: true

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= k <= nums.length
  • nums[i] is 0 or 1

思路:

题目看上去没什么问题,但是不知道为什么差评给得挺多的,而且貌似通过率不算太高,只有60%多。首先如果k等于0则直接返回true即可。然后用一个int cur来记录前一个1的位置,在遍历之前,我们并不知道数组第一位是1还是0,所以cur初始化为-1,这一点比较重要。然后遍历数组,如果当前数字是1,那么判断,只要cur不是-1(说明前面有1),并且当前位置到前一个1的距离小于k,那么就是不满足的,直接return false,否则就是把当前index赋值给cur即可。最终如果能走到函数的return,那么就是满足的,返回true。看上去应该是contest的第一题。

代码:

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

猜你喜欢

转载自blog.csdn.net/weixin_49991368/article/details/113158731