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;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值