100308. 特殊数组 II
如果数组的每一对相邻元素都是两个奇偶性不同的数字,则该数组被认为是一个 特殊数组 。
周洋哥有一个整数数组 nums
和一个二维整数矩阵 queries
,对于 queries[i] = [fromi, toi]
,请你帮助周洋哥检查子数组 nums[fromi..toi]
是不是一个 特殊数组 。
返回布尔数组 answer
,如果 nums[fromi..toi]
是特殊数组,则 answer[i]
为 true
,否则,answer[i]
为 false
。
示例 1:
输入:nums = [3,4,1,2,6], queries = [[0,4]]
输出:[false]
解释:
子数组是 [3,4,1,2,6]
。2 和 6 都是偶数。
示例 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 <= 105
1 <= nums[i] <= 105
1 <= queries.length <= 105
queries[i].length == 2
0 <= queries[i][0] <= queries[i][1] <= nums.length - 1
原站题解
php 解法, 执行用时: 425 ms, 内存消耗: 75.9 MB, 提交时间: 2024-08-14 09:55:37
class Solution { /** * @param Integer[] $nums * @param Integer[][] $queries * @return Boolean[] */ function isArraySpecial($nums, $queries) { $s = array_fill(0, count($nums), 0); for ( $i = 1; $i < count($nums); $i++ ) { $s[$i] = $s[$i-1] + (($nums[$i]^$nums[$i-1]^1)&1); } $ans = array_fill(0, count($queries), false); foreach ($queries as $i => $q ) { $ans[$i] = $s[$q[0]] == $s[$q[1]]; } return $ans; } }
golang 解法, 执行用时: 123 ms, 内存消耗: 18.2 MB, 提交时间: 2024-05-19 23:34:24
func isArraySpecial(nums []int, queries [][]int) []bool { s := make([]int, len(nums)) for i := 1; i < len(nums); i++ { s[i] = s[i-1] + (nums[i]^nums[i-1]^1)&1 } ans := make([]bool, len(queries)) for i, q := range queries { ans[i] = s[q[0]] == s[q[1]] } return ans }
java 解法, 执行用时: 2 ms, 内存消耗: 96 MB, 提交时间: 2024-05-19 23:34:07
class Solution { public boolean[] isArraySpecial(int[] nums, int[][] queries) { int[] s = new int[nums.length]; for (int i = 1; i < nums.length; i++) { s[i] = s[i - 1] + ((nums[i] ^ nums[i - 1] ^ 1) & 1); } boolean[] ans = new boolean[queries.length]; for (int i = 0; i < queries.length; i++) { int[] q = queries[i]; ans[i] = s[q[0]] == s[q[1]]; } return ans; } }
cpp 解法, 执行用时: 206 ms, 内存消耗: 122.9 MB, 提交时间: 2024-05-19 23:33:53
class Solution { public: vector<bool> isArraySpecial(vector<int>& nums, vector<vector<int>>& queries) { vector<int> s(nums.size()); for (int i = 1; i < nums.size(); i++) { s[i] = s[i - 1] + ((nums[i] ^ nums[i - 1] ^ 1) & 1); } vector<bool> ans(queries.size()); for (int i = 0; i < queries.size(); i++) { auto& q = queries[i]; ans[i] = s[q[0]] == s[q[1]]; } return ans; } };
python3 解法, 执行用时: 112 ms, 内存消耗: 45.1 MB, 提交时间: 2024-05-19 23:33:20
class Solution: def isArraySpecial(self, nums: List[int], queries: List[List[int]]) -> List[bool]: s = list(accumulate(((x ^ y ^ 1) & 1 for x, y in pairwise(nums)), initial=0)) return [s[from_] == s[to] for from_, to in queries]