leetcode 1310. XOR Queries of a Subarray

Given the array arr of positive integers and the array queries where queries[i] = [Li, Ri], for each query i compute the XOR of elements from Li to Ri (that is, arr[Li] xor arr[Li+1] xor ... xor arr[Ri] ). Return an array containing the result for the given queries.

 

Example 1:

Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
Output: [2,7,14,8] 
Explanation: 
The binary representation of the elements in the array are:
1 = 0001 
3 = 0011 
4 = 0100 
8 = 1000 
The XOR values for queries are:
[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

Example 2:

Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
Output: [8,0,4,4]

 

Constraints:

  • 1 <= arr.length <= 3 * 10^4
  • 1 <= arr[i] <= 10^9
  • 1 <= queries.length <= 3 * 10^4
  • queries[i].length == 2
  • 0 <= queries[i][0] <= queries[i][1] < arr.length

思路:A[i] 表示[0,i]的所有值的异或,[i, j]的异或为A[j] ^ A[i - 1], 因为x ^ x = 0.

 1 class Solution {
 2 public:
 3     vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) {
 4         for (int i = 1; i < arr.size(); ++i) {
 5             arr[i] ^= arr[i - 1];
 6         }
 7         vector<int> ans(queries.size());
 8         for (int i = 0; i < queries.size(); ++i) {
 9             ans[i] = queries[i][0] > 0 ? arr[queries[i][1]] ^ arr[queries[i][0] - 1] : arr[queries[i][1]];
10         }
11         return ans;
12     }
13 };

python:

1 class Solution:
2     def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
3         for i in range(len(arr) - 1):
4             arr[i + 1] ^= arr[i]
5         return [arr[j] ^ arr[i - 1] if i else arr[j] for i, j in queries]

 

posted @ 2020-01-06 20:55  琴影  阅读(467)  评论(0编辑  收藏  举报