3513. Number of Unique XOR Triplets I 解題紀錄

You are given an integer array nums of length n, where nums is a permutation of the numbers in the range [1, n]. A XOR triplet is defined as the XOR of three elements nums[i] XOR nums[j] XOR nums[k] where i <= j <= k. Return the number of unique XOR triplet values from all possible triplets (i, j, k).   Example 1: Input: nums = [1,2] Output: 2 Explanation: The possible XOR triplet values are: (0, 0, 0) → 1 XOR 1 XOR 1 = 1 (0, 0, 1) → 1 XOR 1 XOR 2 = 2 (0, 1, 1) → 1 XOR 2 XOR 2 = 1 (1, 1, 1) → 2 XOR 2 XOR 2 = 2 The unique XOR values are {1, 2}, so the output is 2. Example 2: Input: nums = [3,1,2] Output: 4 Explanation: The possible XOR triplet values include: (0, 0, 0) → 3 XOR 3 XOR 3 = 3 (0, 0, 1) → 3 XOR 3 XOR 1 = 1 (0, 0, 2) → 3 XOR 3 XOR 2 = 2 (0, 1, 2) → 3 XOR 1 XOR 2 = 0 The unique XOR values are {0, 1, 2, 3}, so the output is 4.   Constraints: 1 <= n == nums.length <= 10^5 1 <= nums[i] <= n nums is a permutation of integers from 1 to n. 這題題目給我們一個一維陣列 nums, 並且希望我們每次從這些陣列元素裡面選三個(可重複)來 XOR, 想問最多有幾個獨特的 XOR 值? 假設 nums 的長度等於 N。 這題有兩個關鍵, - XOR 相同元素相乘會等於 0,所以可以重複的元素可以佔兩格 -> 所以只要元素數量大於 3,就會至少會有 N 個獨立元素。 - XOR 是單調收斂,所以任意元素 XOR 無限次最多只會湊出這個元素區間的所有值,可以透過二進位驗證。 不過這裡有個例外,當長度 N = 1 or 2 的時候只能湊出 1 or 2 XOR 值, 是特例要特別避開。 C++程式碼:
megapx
計算複雜度:O(1) 空間複雜度:O(1) Github程式碼:
MurMur: 這題的第二個約束我也是看提示看很久,誰會想到用這樣解QQ
愛心
98
留言
encourage first comment
有些話想說嗎 快分享出來彼此交流吧!