GoCalf Calf 的自留地 · 昙花一现

3151. Special Array I

Problem

An array is considered special if every pair of its adjacent elements contains two numbers with different parity.

You are given an array of integers nums. Return true if nums is a special array, otherwise, return false.

https://leetcode.com/problems/special-array-i/

Example 1:

Input: nums = [1]
Output: true
Explanation:
There is only one element. So the answer is true.

Example 2:

Input: nums = [2,1,4]
Output: true
Explanation:
There is only two pairs: (2,1) and (1,4), and both of them contain numbers with different parity. So the answer is true.

Example 3:

Input: nums = [4,3,1,6]
Output: false
Explanation:
nums[1] and nums[2] are both odd. So the answer is false.

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

Test Cases

python
class Solution:
    def isArraySpecial(self, nums: List[int]) -> bool:
solution_test.py下载完整源码
py
import pytest

from solution import Solution


@pytest.mark.parametrize('nums, expected', [
    ([1], True),
    ([2,1,4], True),
    ([4,3,1,6], False),
])
class Test:
    def test_solution(self,nums, expected):
        sol = Solution()
        assert sol.isArraySpecial(nums) == expected

Thoughts

Code

py
class Solution:
    def isArraySpecial(self, nums: list[int]) -> bool:
        prev = nums[0] & 1
        for i in range(1, len(nums)):
            if nums[i] & 1 == prev:
                return False
            prev = 1 - prev

        return True

评论需要 JavaScript。