[Swift]LeetCode421. 数组中两个数的最大异或值 | Maximum XOR of Two Numbers in an Array
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:为敢(WeiGanTechnologies)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10333729.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.
Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
Could you do this in O(n) runtime?
Example:
Input: [3, 10, 5, 25, 2, 8] Output: 28 Explanation: The maximum result is 5 ^ 25 = 28.
给定一个非空数组,数组中元素为 a0, a1, a2, … , an-1,其中 0 ≤ ai < 231 。
找到 ai 和aj 最大的异或 (XOR) 运算结果,其中0 ≤ i, j < n 。
你能在O(n)的时间解决这个问题吗?
示例:
输入: [3, 10, 5, 25, 2, 8] 输出: 28 解释: 最大的结果是 5 ^ 25 = 28.
196ms
1 class Solution { 2 func findMaximumXOR(_ nums: [Int]) -> Int { 3 var res:Int = 0 4 var mask:Int = 0 5 for i in (0...31).reversed() 6 { 7 mask |= (1 << i) 8 var s:Set<Int> = Set<Int>() 9 for num in nums 10 { 11 s.insert(num & mask) 12 } 13 var t:Int = res | (1 << i) 14 for prefix in s 15 { 16 if s.contains(t ^ prefix) 17 { 18 res = t 19 break 20 } 21 } 22 } 23 return res 24 } 25 }
872ms
1 class TrieNode { 2 var children = [Int: TrieNode]() 3 var end: Bool 4 var value: Int = -1 5 6 init() { 7 end = false 8 } 9 10 func hasChild(_ key: Int) -> Bool { 11 return children[key] != nil 12 } 13 14 func makeChild(_ key: Int) { 15 children[key] = TrieNode() 16 } 17 18 func getChild(_ key: Int) -> TrieNode { 19 return children[key]! 20 } 21 } 22 23 24 class Solution { 25 26 let INT_SIZE = 32 27 var root = TrieNode() 28 29 func findMaximumXOR(_ nums: [Int]) -> Int { 30 31 var ans = 0 32 insert(nums[0]) 33 34 for i in 1..<nums.count { 35 ans = max(ans, query(nums[i])) 36 insert(nums[i]) 37 } 38 39 return ans 40 41 } 42 43 func query(_ key: Int) -> Int { 44 var current = root 45 46 for i in (0..<INT_SIZE).reversed() { 47 let current_bit = (key & 1<<i) >= 1 ? 1 : 0 48 let next: TrieNode? 49 if current.hasChild(1-current_bit) { 50 next = current.getChild(1-current_bit) 51 } else { 52 next = current.getChild(current_bit) 53 } 54 55 current = next! 56 } 57 58 return key ^ current.value 59 60 } 61 62 func insert(_ num: Int) { 63 64 var current = root 65 66 for i in (0..<INT_SIZE).reversed() { 67 let key = (num & 1<<i) >= 1 ? 1 : 0 68 if !current.hasChild(key) { 69 current.makeChild(key) 70 } 71 72 current = current.getChild(key) 73 } 74 75 current.end = true 76 current.value = num 77 } 78 }