chenfy27的刷题记录

导航

leetcode2935 找出强数对的最大异或值II

给定数组nums[n],如果一对整数x和y满足|x-y|<=min(x,y),则称其为强数对。需要从nums[n]中选出一个强数对,并且异或结果最大。
1<=n<=5E4; 1<=nums[i]<2^20

分析:trie+双指针。不妨设x<=y,对|x-y|<=min(x,y)变形得:x<=y<=2x,也就是说只能在[x,2x]范围内选择,可以用双指针来维护有效范围。

// 01-trie模板。。。

class Solution {
public:
    int maximumStrongPairXor(vector<int>& nums) {
        int n = nums.size();
        std::sort(nums.begin(), nums.end());

        Trie tr;
        tr.init(1 << 20);
        int ans = 0;
        for (int L = 0, R = 0; L < n; L++) {
            while (R < n && nums[R] <= 2 * nums[L]) {
                tr.insert(nums[R]);
                R += 1;
            }
            ans = std::max(ans, nums[L] ^ tr.find(nums[L]));
            tr.remove(nums[L]);
        }
        return ans;
    }
};

posted on 2024-12-29 15:58  chenfy27  阅读(11)  评论(0)    收藏  举报