421.maximum-xor-of-two-numbers-in-an-array.go 458 B

123456789101112131415161718
  1. func findMaximumXOR(nums []int) int {
  2. max, mask := 0, 0
  3. for i := 31; 0 <= i; i-- { // Check max & 1<<i is 1 or 0
  4. m := make(map[int]bool)
  5. mask |= 1 << uint(i)
  6. for _, n := range nums {
  7. m[n&mask] = true // Get the top n digit of nums as prefix set
  8. }
  9. tmp := max | 1<<uint(i) // Assume that c == max | 1<<i, for each a, find if b is in prefix set
  10. for k := range m {
  11. if _, ok := m[tmp^k]; ok {
  12. max = tmp
  13. break
  14. }
  15. }
  16. }
  17. return max
  18. }