在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given the array
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 = [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]
提示:
Runtime: 556 ms
Memory Usage: 25.7 MB
1 class Solution { 2 func xorQueries(_ arr: [Int], _ queries: [[Int]]) -> [Int] { 3 var arr = arr 4 var res:[Int] = [Int](repeating:0,count:queries.count) 5 var q:[Int] = [Int]() 6 for i in 1..<arr.count 7 { 8 arr[i] ^= arr[i - 1] 9 } 10 for i in 0..<queries.count 11 { 12 q = queries[i] 13 res[i] = q[0] > 0 ? arr[q[0] - 1] ^ arr[q[1]] : arr[q[1]] 14 } 15 return res 16 } 17 } Runtime: 540 ms
Memory Usage: 26.2 MB
1 class Solution { 2 func xorQueries(_ arr: [Int], _ queries: [[Int]]) -> [Int] { 3 var prefix = Array<Int>(repeating: 0, count: arr.count + 1) 4 for index in 0..<arr.count { 5 prefix[index + 1] = prefix[index] ^ arr[index] 6 } 7 return queries.map {prefix[$0[0]] ^ prefix[$0[1] + 1]} 8 } 9 }
|
请发表评论