当前位置: 首页 > >

1310. 子数组异或查询

发布时间:

1310. 子数组异或查询


难度中等60收藏分享切换为英文接收动态反馈


有一个正整数数组?arr,现给你一个对应的查询数组?queries,其中?queries[i] = [Li,?Ri]


对于每个查询?i,请你计算从?Li?到?Ri?的?XOR?值(即?arr[Li]?xor?arr[Li+1]?xor?...?xor?arr[Ri])作为本次查询的结果。


并返回一个包含给定查询?queries?所有结果的数组。


?


示例 1:


输入:arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
输出:[2,7,14,8]
解释:
数组中元素的二进制表示形式是:
1 = 0001
3 = 0011
4 = 0100
8 = 1000
查询的 XOR 值为:
[0,1] = 1 xor 3 = 2
[1,2] = 3 xor 4 = 7
[0,3] = 1 xor 3 xor 4 xor 8 = 14
[3,3] = 8

示例 2:


输入:arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
输出:[8,0,4,4]

?


提示:


1 <= arr.length <= 3 *?10^41 <= arr[i] <= 10^91 <= queries.length <= 3 * 10^4queries[i].length == 20 <= queries[i][0] <= queries[i][1] < arr.length

1.暴力解法:O(n^2),超时


n, m = len(arr), len(queries)
if n == 0:
return []
res = []
# for i in range(m):
# if queries[i][0] > queries[i][1] or queries[i][1] >= n:
# return []
# tmp = 0
# for j in range(queries[i][0],queries[i][1]+1):
# tmp ^= arr[j]
# res.append(tmp)
# return res

2.类似前n个数之和:t = s = O(N)


class Solution:
def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
n, m = len(arr), len(queries)
if n == 0:
return []
record, res = [], []
tmp = 0
for i in arr:
tmp ^= i
record.append(tmp)
for i in range(m):
if queries[i][0] > queries[i][1] or queries[i][1] >= n:
return []
#注意下边首个数不能遗漏
res.append(arr[queries[i][0]]^record[queries[i][0]] ^ record[queries[i][1]])
return res


?



友情链接: