leetcode - 2425. Bitwise XOR of All Pairings
Description
You are given two 0-indexed arrays, nums1 and nums2, consisting of non-negative integers. There exists another array, nums3, which contains the bitwise XOR of all pairings of integers between nums1 and nums2 (every integer in nums1 is paired with every integer in nums2 exactly once).
Return the bitwise XOR of all integers in nums3.
Example 1:
Input: nums1 = [2,1,3], nums2 = [10,2,5,0]
Output: 13
Explanation:
A possible nums3 array is [8,0,7,2,11,3,4,1,9,1,6,3].
The bitwise XOR of all these numbers is 13, so we return 13.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 0
Explanation:
All possible pairs of bitwise XORs are nums1[0] ^ nums2[0], nums1[0] ^ nums2[1], nums1[1] ^ nums2[0],
and nums1[1] ^ nums2[1].
Thus, one possible nums3 array is [2,5,1,6].
2 ^ 5 ^ 1 ^ 6 = 0, so we return 0.
Constraints:
1 <= nums1.length, nums2.length <= 10^5
0 <= nums1[i], nums2[j] <= 10^9
Solution
Assume nums1 = [x, y], nums2 = [a,b,c]
, then nums3 = [x^a, x^b, x^c, y^a, y^b, y^c]
, so the result would be: x^a^x^b^x^c^y^a^y^b^y^c = (x^x^x)^(y^y^y)^(a^a)^(b^b)^(c^c)
, so if the length of nums1
is odd, then we xor all the elements in nums2
, otherwise we get 0
from nums2’s xor.
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
1
)
o(1)
o(1)
Code
class Solution:
def xorAllNums(self, nums1: List[int], nums2: List[int]) -> int:
res = 0
if len(nums1) & 1 == 1:
for each_num in nums2:
res ^= each_num
if len(nums2) & 1 == 1:
for each_num in nums1:
res ^= each_num
return res
原文地址:https://blog.csdn.net/sinat_41679123/article/details/145174348
免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!