当前位置:网站首页>LeetCode 1550. There are three consecutive arrays of odd numbers

LeetCode 1550. There are three consecutive arrays of odd numbers

2022-07-06 16:42:00 Daylight629

1550. There are three consecutive odd arrays

Give you an array of integers arr, Please judge whether three consecutive elements in the array are odd : If there is , Please return true ; otherwise , return false .

Example 1:

 Input :arr = [2,6,4,1]
 Output :false
 explain : There is no case where three consecutive elements are odd .

Example 2:

 Input :arr = [1,2,34,3,4,5,7,23,12]
 Output :true
 explain : There is a case where three consecutive elements are odd , namely  [5,7,23] .

Tips :

  • 1 <= arr.length <= 1000
  • 1 <= arr[i] <= 1000

Two 、 Method 1

enumeration

class Solution {
    
    public boolean threeConsecutiveOdds(int[] arr) {
    
        int k = 0;
        for (int i = 0; i < arr.length; i++) {
    
            if ((arr[i] & 1) == 1) {
    
                k++;
                if (k == 3) {
    
                    return true;
                }
            } else {
    
                k = 0;
            }
        }
        return false;
    }
}

Complexity analysis

  • Time complexity :O(n).
  • Spatial complexity :O(1).

3、 ... and 、 Method 2

enumeration

class Solution {
    
    public boolean threeConsecutiveOdds(int[] arr) {
    

        for (int i = 0; i < arr.length - 2; i++) {
    
            if ((arr[i] & 1) == 1 && (arr[i + 1] & 1) == 1 && (arr[i + 2] & 1) == 1) {
    
                return true;
            }
               
        }
        return false;
    }
}

Complexity analysis

  • Time complexity :O(n).
  • Spatial complexity :O(1).
原网站

版权声明
本文为[Daylight629]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131315404454.html