zoukankan      html  css  js  c++  java
  • 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
    class Solution {
        public int[] xorQueries(int[] arr, int[][] queries) {
            int[] res = new int[queries.length];
            int ql = queries.length;
            for(int i = 0; i < ql; i++){
                res[i] = help(arr, queries[i][0], queries[i][1]);
            }
            return res;
        }
        public int help(int[] arr, int l, int r){
            int re = 0;
            if(l == r) return arr[l];
            while(l <= r){
                re = arr[l] ^ (arr[r] ^ re);
                l++;
                r--;
                if(l == r) return re ^ arr[l];
            }
            return re;
        }
    }

    0和任何数异或数值不变

    然后就直接解,大概是O(n/2),注意判断l和r的大小关系

  • 相关阅读:
    c++ 左值和右值
    C++的顶层const和底层const的理解
    TCP/IP模型中的网络层
    有关TCP/IP模型中的网络接入层
    计算机网络协议与IPv4地址
    浅析计算机网络
    海思Android开发平台如何自定义update.zip内容
    Android平台RTL蓝牙适配偶现打不开问题调试笔记
    Android的SoundPool
    Android开发之IntentService
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12169413.html
Copyright © 2011-2022 走看看