herrDeng網內搜尋

自訂搜尋

Ads

2024年11月8日 星期五

XOR prefix sum C++ python解Leetcode 1829 Maximum XOR for Each Query


XOR prefixsum CPP python解Leetcode 1829  Maximum XOR for Each Query
其實這裡考慮的是元素個數為2^maximumBit的交換群,運算子為XOR。
[Python code請進]
bitwise XOR has the perfect algebaic properties, e.g. x^x=0, x^y=y^x, x^(~x)=0
x^k=y implies x^k^x=k=y^x
  1. class Solution:
  2. def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:
  3. #bitwise XOR has the perfect algebaic properties, e.g. x^x=0, x^y=y^x, x^(~x)=0
  4. #x^k=y=> x^k^x=k=y^x
  5. mask, n=(2**maximumBit-1, len(nums)
  6. ans=[0]*n
  7. ans[-1]=nums[0]^mask
  8. for i in range(1, n):
  9. ans[~i]^=(ans[n-i]^nums[i])
  10. return ans

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章