mirror of https://github.com/doocs/leetcode.git
5.2 KiB
5.2 KiB
| comments | difficulty | edit_url | rating | source | tags | |||
|---|---|---|---|---|---|---|---|---|
| true | 中等 | https://github.com/doocs/leetcode/edit/main/solution/3100-3199/3152.Special%20Array%20II/README.md | 1523 | 第 398 场周赛 Q2 |
|
3152. 特殊数组 II
题目描述
如果数组的每一对相邻元素都是两个奇偶性不同的数字,则该数组被认为是一个 特殊数组 。
你有一个整数数组 nums 和一个二维整数矩阵 queries,对于 queries[i] = [fromi, toi],请你帮助你检查 子数组 nums[fromi..toi] 是不是一个 特殊数组 。
返回布尔数组 answer,如果 nums[fromi..toi] 是特殊数组,则 answer[i] 为 true ,否则,answer[i] 为 false 。
示例 1:
示例 2:
输入:nums = [4,3,1,6], queries = 0,2],[2,3
输出:[false,true]
解释:
- 子数组是
[4,3,1]。3 和 1 都是奇数。因此这个查询的答案是false。 - 子数组是
[1,6]。只有一对:(1,6),且包含了奇偶性不同的数字。因此这个查询的答案是true。
提示:
1 <= nums.length <= 1051 <= nums[i] <= 1051 <= queries.length <= 105queries[i].length == 20 <= queries[i][0] <= queries[i][1] <= nums.length - 1
解法
方法一:记录每个位置的最左特殊数组位置
我们可以定义一个数组 d 来记录每个位置的最左特殊数组位置,初始时 d[i] = i。然后我们从左到右遍历数组 nums,如果 nums[i] 和 nums[i - 1] 的奇偶性不同,那么 d[i] = d[i - 1]。
最后我们遍历每个查询,判断 d[to] <= from 是否成立即可。
时间复杂度 O(n),空间复杂度 O(n)。其中 n 是数组的长度。
Python3
class Solution:
def isArraySpecial(self, nums: List[int], queries: List[List[int]]) -> List[bool]:
n = len(nums)
d = list(range(n))
for i in range(1, n):
if nums[i] % 2 != nums[i - 1] % 2:
d[i] = d[i - 1]
return [d[t] <= f for f, t in queries]
Java
class Solution {
public boolean[] isArraySpecial(int[] nums, int[][] queries) {
int n = nums.length;
int[] d = new int[n];
for (int i = 1; i < n; ++i) {
if (nums[i] % 2 != nums[i - 1] % 2) {
d[i] = d[i - 1];
} else {
d[i] = i;
}
}
int m = queries.length;
boolean[] ans = new boolean[m];
for (int i = 0; i < m; ++i) {
ans[i] = d[queries[i][1]] <= queries[i][0];
}
return ans;
}
}
C++
class Solution {
public:
vector<bool> isArraySpecial(vector<int>& nums, vector<vector<int>>& queries) {
int n = nums.size();
vector<int> d(n);
iota(d.begin(), d.end(), 0);
for (int i = 1; i < n; ++i) {
if (nums[i] % 2 != nums[i - 1] % 2) {
d[i] = d[i - 1];
}
}
vector<bool> ans;
for (auto& q : queries) {
ans.push_back(d[q[1]] <= q[0]);
}
return ans;
}
};
Go
func isArraySpecial(nums []int, queries [][]int) (ans []bool) {
n := len(nums)
d := make([]int, n)
for i := range d {
d[i] = i
}
for i := 1; i < len(nums); i++ {
if nums[i]%2 != nums[i-1]%2 {
d[i] = d[i-1]
}
}
for _, q := range queries {
ans = append(ans, d[q[1]] <= q[0])
}
return
}
TypeScript
function isArraySpecial(nums: number[], queries: number[][]): boolean[] {
const n = nums.length;
const d: number[] = Array.from({ length: n }, (_, i) => i);
for (let i = 1; i < n; ++i) {
if (nums[i] % 2 !== nums[i - 1] % 2) {
d[i] = d[i - 1];
}
}
return queries.map(([from, to]) => d[to] <= from);
}