【Leecode笔记】第二十周(1.24-1.30) 数组专题

【第一题】是否所有的1都至少相隔k个元素

分析:双指针。两个指针指向相邻的两个1,下标相减假如都>3,那么符合。

//不是吧阿sir,这么慢吗?
//执行用时:3 ms, 在所有 Java 提交中击败了11.40% 的用户
//内存消耗:48.3 MB, 在所有 Java 提交中击败了61.52% 的用户
class Solution {
   
    public boolean kLengthApart(int[] nums, int k) {
   
        if(nums.length == 1){
   return false;}
        if(nums.length == 2){
   
            if(k == 0){
   
                return true;
            }
            else if(k == 1){
   
                if(nums[0] == 0 || nums[1] == 0){
   return true;}
                else{
   return false;}
            }
        }
        int i = 0,j = 1;
        while(i < nums.length && j < nums.length){
   
            if(nums[i] == 1 && nums[j] == 1){
   
                if(j - i >= k+1){
   
                    i = j;
                    if(j < nums.length-1){
   
                        j++;
                    }else{
   
                        break;
                    }
                }else{
   
                    return false;
                }
            }
            if(nums[i]!=1){
   
                i++;/
                j = i+1;
            }
            if(nums[j]!=1){
   
                j++;
            }
        }
        return true;
    }
}
//执行用时:1 ms, 在所有 Java 提交中击败了100.00% 的用户
//内存消耗:48.2 MB, 在所有 Java 提交中击败了66.12% 的用户
class Solution {
   
    public boolean kLengthApart(int[] nums, int k) {
   
        int before = -100000;
        for(int i = 0 ;i<nums.length;i++){
   
            if(nums[i]==1){
   
                if(i-before-1<k) 

你可能感兴趣的:(Leecode,leetcode,数组)