chenfy27的刷题记录

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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   chenfy27  阅读(3)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示