This article is participating in Python Theme Month. See the link for details

describe

Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.

Example 1:

Input: arr = [2,6,4,1]
Output: false
Explanation: There are no three consecutive odds.
Copy the code

Example 2:

Input: arr = [1,2,34,3,4,5,7,23,12]
Output: true
Explanation: [5,7,23] are three consecutive odds.
Copy the code

Note:

1 <= arr.length <= 1000
1 <= arr[i] <= 1000
Copy the code

parsing

There are three connected odd numbers in arR. If it is odd, increment it by one. If it is not odd, reset it to 0. Return True if count is greater than or equal to 3.

answer

class Solution(object):
    def threeConsecutiveOdds(self, arr):
        """
        :type arr: List[int]
        :rtype: bool
        """
        count = 0
        for i,v in enumerate(arr):
            if v%2:
                count+=1
                if count==3:
                    return True
            else:
                count = 0
        return False

        	      
		
Copy the code

The results

Given in the Python online submissions for Three Consecutive Odds. Memory Usage: Given in the Python online submissions for Three Consecutive Odds.Copy the code

parsing

Although the principle of the following is the same, the solution is novel, because the characteristic of odd numbers is that the modulo of 2 produces 1, and the modulo of 3 connected odd numbers of 2 produces 3 ones. Modulo every number in arR into a string and concatenate the result into a string, and then just check if the string 111 is in it.

answer

class Solution(object):
    def threeConsecutiveOdds(self, arr):
        """
        :type arr: List[int]
        :rtype: bool
        """
        return "111" in "".join([str(i%2) for i in arr])
Copy the code

The results

Given in the linked list. Memory Usage: 10 ms for each node in the linked list. The linked submissions in Python online submissions for Three Consecutive Odds.Copy the code

parsing

This algorithm is used to compare rare bitwise and operation &, because some digital bitwise and operation with 1, when the number is odd number calculation result is 1, when the number is even number calculation result is 0, so you can continue to use the ideas above, for each element of arr for 1 first do bitwise and operation, The result is then concatenated into a string, and you just need to determine if the string 111 appears in it.

answer

class Solution(object):
    def threeConsecutiveOdds(self, arr):
        """
        :type arr: List[int]
        :rtype: bool
        """
        return '111' in ''.join([str(i&1) for i in arr])
        
Copy the code

The results

Given in the linked list. Memory Usage: 10 ms for each node in the linked list. 13 MB, less than 67.31% of Python online submissions for Three Consecutive Odds.Copy the code

Original link: leetcode.com/problems/th…

Your support is my biggest motivation