chenfy27的刷题记录

导航

leetcode1803 统计异或值在范围内的数对有多少

给定数组nums[n]和两个整数low与high,问有多少对(i,j)满足 0<=i<j<n,并且low <= (nums[i] ^ nums[j]) <= high。
1<=n<=2E4; 1<=nums[i]<=2E4; 1<=low<=high<=2E4

分析:
1、把区分问题拆分为两部分,记f(x)表示不超过x的个数,那么f(high) - f(low-1)就是答案,只需要实现f(x)即可。
2、从高到低逐位分析:
(1)如果某一位上x为1,那么不论选0或1,异或结果都不会超过1,此时把相同的个数加入答案,继续跟进不同的路径。
(2)如果某一位为x为0,那只能选相同的路径,这样异或结果才为0。
(3)进入最下一层时,都是满足条件的,需要加入结果。

// 01-trie 模板。。。

class Solution {
public:
    int countPairs(vector<int>& nums, int low, int high) {
        Trie tr;
        tr.init(2E4);
        int ans = 0;
        int n = nums.size();
        for (int i = 0; i < n; i++) {
            if (tr.size() > 0) {
                ans += tr.find(nums[i], high) - tr.find(nums[i], low - 1);
            }
            tr.insert(nums[i]);
        }
        return ans;
    }
};

posted on 2024-12-29 19:37  chenfy27  阅读(13)  评论(0)    收藏  举报