跳至主要內容

3151. 特殊数组 I


3151. 特殊数组 I

🟢   🔖  数组  🔗 力扣open in new window LeetCodeopen in new window

题目

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.

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

题目大意

如果数组的每一对相邻元素都是两个奇偶性不同的数字,则该数组被认为是一个 特殊数组

你有一个整数数组 nums。如果 nums 是一个 特殊数组 ,返回 true,否则返回 false

示例 1:

输入: nums = [1]

输出: true

解释:

只有一个元素,所以答案为 true

示例 2:

输入: nums = [2,1,4]

输出: true

解释:

只有两对相邻元素: (2,1)(1,4),它们都包含了奇偶性不同的数字,因此答案为 true

示例 3:

输入: nums = [4,3,1,6]

输出: false

解释:

nums[1]nums[2] 都是奇数。因此答案为 false

提示:

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

解题思路

  1. 按位与操作 & 判断奇偶性

    • num & 1 == 0 代表 num 为偶数。
    • num & 1 == 1 代表 num 为奇数。
  2. 异或运算 ^ 检查奇偶交替性

    • 对比 (nums[i] & 1)(nums[i + 1] & 1)
      • 若不相等,表示 nums[i]nums[i + 1] 奇偶不同(符合交替条件)。
      • 若相等,表示相邻数字的奇偶性相同,不符合要求,直接返回 false

复杂度分析

  • 时间复杂度O(n),需要遍历数组一次。
  • 空间复杂度O(1),只使用常数额外空间。

代码

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var isArraySpecial = function (nums) {
	for (let i = 0; i < nums.length - 1; i++) {
		if ((nums[i] & 1) === (nums[i + 1] & 1)) return false;
	}
	return true;
};