|
| 1 | +// Source : https://leetcode.com/problems/maximum-xor-for-each-query/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-04-20 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * You are given a sorted array nums of n non-negative integers and an integer maximumBit. You want to |
| 8 | + * perform the following query n times: |
| 9 | + * |
| 10 | + * Find a non-negative integer k < 2^maximumBit such that nums[0] XOR nums[1] XOR ... XOR |
| 11 | + * nums[nums.length-1] XOR k is maximized. k is the answer to the i^th query. |
| 12 | + * Remove the last element from the current array nums. |
| 13 | + * |
| 14 | + * Return an array answer, where answer[i] is the answer to the i^th query. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * |
| 18 | + * Input: nums = [0,1,1,3], maximumBit = 2 |
| 19 | + * Output: [0,3,2,3] |
| 20 | + * Explanation: The queries are answered as follows: |
| 21 | + * 1^st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. |
| 22 | + * 2^nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. |
| 23 | + * 3^rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3. |
| 24 | + * 4^th query: nums = [0], k = 3 since 0 XOR 3 = 3. |
| 25 | + * |
| 26 | + * Example 2: |
| 27 | + * |
| 28 | + * Input: nums = [2,3,4,7], maximumBit = 3 |
| 29 | + * Output: [5,2,6,5] |
| 30 | + * Explanation: The queries are answered as follows: |
| 31 | + * 1^st query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. |
| 32 | + * 2^nd query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. |
| 33 | + * 3^rd query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7. |
| 34 | + * 4^th query: nums = [2], k = 5 since 2 XOR 5 = 7. |
| 35 | + * |
| 36 | + * Example 3: |
| 37 | + * |
| 38 | + * Input: nums = [0,1,2,2,5,7], maximumBit = 3 |
| 39 | + * Output: [4,3,6,4,6,7] |
| 40 | + * |
| 41 | + * Constraints: |
| 42 | + * |
| 43 | + * nums.length == n |
| 44 | + * 1 <= n <= 10^5 |
| 45 | + * 1 <= maximumBit <= 20 |
| 46 | + * 0 <= nums[i] < 2^maximumBit |
| 47 | + * nums is sorted in ascending order. |
| 48 | + ******************************************************************************************************/ |
| 49 | + |
| 50 | +class Solution { |
| 51 | +public: |
| 52 | + vector<int> getMaximumXor(vector<int>& nums, int maximumBit) { |
| 53 | + int all = 0; |
| 54 | + for(auto& n : nums) { |
| 55 | + all ^= n; |
| 56 | + } |
| 57 | + |
| 58 | + int max = (1 << maximumBit) - 1; |
| 59 | + vector<int> result; |
| 60 | + for(int i = nums.size()-1; i>=0; i--) { |
| 61 | + result.push_back(all ^ max); |
| 62 | + all ^= nums[i]; |
| 63 | + } |
| 64 | + |
| 65 | + return result; |
| 66 | + } |
| 67 | +}; |
0 commit comments