classSolution: defsingleNumber(self, nums: List[int]) -> int: ret = [0] * 33 for x in nums: for i inrange(32): ret[i] += ((x>>i) & 1) ans = 0 for i inrange(32): if ret[i] % 3 != 0: if i == 31: ans -= (1 << i) else: ans |= (1 << i) return ans
classSolution { public: intsingleNumber(vector<int>& nums){ int ans = 0; int ret[32] = {0}; for (auto x : nums) { for (int i = 0; i < 32; i++) { ret[i] += ((x >> i) & 1); } } for (int i = 0; i < 32; i++) { if (ret[i] % 3 != 0) ans += (1 << i); } return ans; } };
classSolution: defsingleNumber(self, nums: List[int]) -> List[int]: xorsum = 0 for x in nums: xorsum ^= x ans1 = ans2 = 0 lb = xorsum & (-xorsum) for x in nums: if lb & x: ans1 ^= x else: ans2 ^= x
classSolution: defsubsets(self, nums: List[int]) -> List[List[int]]: n = len(nums) rets = [] i = 0 while i < (1<<n): ret = [] for j inrange(n): if (i >> j) & 1 == 1: ret.append(nums[j]) rets.append(ret) i += 1 return rets
x ^ new_ans 如果在seen里找到了 说明seen里一定有一个数 y 满足 x ^ y == new_ans (因为a ^ b = c <=> a ^ c = b <,=> b ^ c = a)那就说明 有两个数的异或值 可以为new_ans (也即在保留前i - 1位的情况下 第i位可以为1) 如果没有找到的话 就说明不存在两个数异或为new_ans 那ans就不变 (即该位为0不变)否则ans = new_ans 这样 每一位都尽量取1 最后就是最大值
主要用了 用mask与 取前缀排除后缀的影响 不是只比较第i位 而是比较前i位
设new_ans 去异或 然后在set里查找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: deffindMaximumXOR(self, nums: List[int]) -> int: ans = mask = 0 high_bit = max(nums).bit_length() - 1 for i inrange(high_bit, -1, -1): mask = 1 |= (1 << i) seen = set() new_ans = ans |= (1 << i) for x in nums: x &= mask if (x ^ new_ans) in seen(): ans = new_ans break seen.add(x) return ans
defadd(num: int): cut = root for k inrange(high_bit, -1, -1): bit = (num >> k) & 1 if bit == 0: if cur.left isNone: cur.left = Trie() cur = cur.left else: if cur.right isNone: cur.right = Trie() cur = cur.right
defcheck(num: int): cur = root x = 0 for k inrange(high_bit, -1, -1): bit = (num >> k) & 1 if bit == 0: if cur.right: cur = cur.right x = x * 2 + 1 else: cur = cur.left x = x * 2 else: if cur.left: cur = cur.left x = x * 2 + 1 else: cur = cur.right x = x * 2 return x
x = 0 n = len(nums) for i inrange(1, n): add(nums[i - 1]) x = max(x, check(nums[i])) return x