1 class Solution: 2 def xorQueries(self, arr: 'List[int]', queries: 'List[List[int]]') -> 'List[int]': 3 n = len(arr) 4 prefixsum = [arr[0]] * n 5 res = [] 6 for i in range(1,n): 7 prefixsum[i] = prefixsum[i-1] ^ arr[i] 8 9 m = len(queries) 10 for i in range(m): 11 begin = queries[i][0] 12 end = queries[i][1] 13 if begin == 0: 14 cur = prefixsum[end] 15 else: 16 cur = prefixsum[end] ^ prefixsum[begin-1] 17 res.append(cur) 18 return res
Algorithm thinking: bit computing. The nature of the exclusive-OR operation are: x ^ x = 0, and x ^ 0 = x.
XOR array prefixsum order before Mr. Cheng.
For the closed interval [begin, end], only need to use a boundary position prefixsum corresponding to XOR.
If begin == 0, the calculation result is prefixsum [end];
If begin> 0, is calculated activation prefixsum [end] - prefixsum [begin-1].