在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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 }
|
请发表评论