刷题总结#4

来源:互联网 发布:人体工程学鼠标 知乎 编辑:程序博客网 时间:2024/05/22 06:55

#421
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.
Input: [3, 10, 5, 25, 2, 8]

Output: 28

Explanation: The maximum result is 5 ^ 25 = 28.
挺有意思的一个题。异或的题一般都是从每一位整体的情况入手。
主要得明白 A^B=C , A^C=B;
我们从高位入手,用10000……, 11000……,这样的数&去获取高位。

 int ans=0;        int bar=0;        for(int i=30;i>=0;i--)        {            bar|=1 < < i;            unordered_set<int>pq;            for(int j=0;j < nums.size();j++)            {                pq.insert(nums[j]&bar);            }            //获取高位,然后放到pq的set里面            int tmp=ans|1 < < i;//假设这一位可以加到ans里面            for(auto &it:pq)            {                if(pq.find(it^tmp)!=pq.end()) 通过A^ans找B来判断是否ans成立                {                    ans=tmp;                    break;                }            }        }        return ans;
0 0