跳转至

3875. 构造奇偶一致的数组 I

题目描述

给你一个长度为 n 的数组 nums1,其中包含 互不相同 的整数。

你需要构造另一个长度为 n 的数组 nums2,使得 nums2 中的元素要么全部为 奇数,要么全部为 偶数

对于每个下标 i,你必须从以下两种选择中 任选其一(顺序不限):

  • nums2[i] = nums1[i]
  • nums2[i] = nums1[i] - nums1[j],其中 j != i

如果能够构造出满足条件的数组,则返回 true;否则,返回 false

 

示例 1:

输入: nums1 = [2,3]

输出: true

解释:

  • 选择 nums2[0] = nums1[0] - nums1[1] = 2 - 3 = -1
  • 选择 nums2[1] = nums1[1] = 3
  • nums2 = [-1, 3],两个元素均为奇数。因此答案为 true

示例 2:

输入: nums1 = [4,6]

输出: true

解释:​​​​​​​

  • 选择 nums2[0] = nums1[0] = 4
  • 选择 nums2[1] = nums1[1] = 6
  • nums2 = [4, 6],两个元素均为偶数。因此答案为 true

 

提示:

  • 1 <= n == nums1.length <= 100
  • 1 <= nums1[i] <= 100
  • nums1 中的所有整数互不相同。

解法

方法一:脑筋急转弯

如果 \(\textit{nums1}\) 中的所有元素全是奇数或者全是偶数,那么我们可以直接将 \(\textit{nums2}\) 设为 \(\textit{nums1}\),满足条件。

如果 \(\textit{nums1}\) 中既有奇数又有偶数,那么我们可以将 \(\textit{nums2}\) 中的每个元素都设为 \(\textit{nums1}\) 的当前元素减去 \(\textit{nums1}\) 中的一个与当前元素奇偶性不同的元素。由于奇数减偶数和偶数减奇数的结果都是奇数,因此 \(\textit{nums2}\) 中的所有元素都是奇数,满足条件。

因此,无论 \(\textit{nums1}\) 中的元素是全奇数、全偶数,还是既有奇数又有偶数,我们都可以构造出满足条件的 \(\textit{nums2}\)。所以答案始终是 \(\text{true}\)

时间复杂度 \(O(1)\),空间复杂度 \(O(1)\)

1
2
3
class Solution:
    def uniformArray(self, nums1: list[int]) -> bool:
        return True
1
2
3
4
5
class Solution {
    public boolean uniformArray(int[] nums1) {
        return true;
    }
}
1
2
3
4
5
6
class Solution {
public:
    bool uniformArray(vector<int>& nums1) {
        return true;
    }
};
1
2
3
func uniformArray(nums1 []int) bool {
    return true
}
1
2
3
function uniformArray(nums1: number[]): boolean {
    return true;
}

评论