Skip to content

Commit d3f4125

Browse files
committed
https://leetcode.cn/problems/count-pairs-with-xor-in-a-range
1 parent 149a8f0 commit d3f4125

File tree

3 files changed

+69
-4
lines changed

3 files changed

+69
-4
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ Step 2. Add the dependency
4949

5050
<summary>展开查看</summary>
5151

52+
https://leetcode.cn/problems/count-pairs-with-xor-in-a-range
53+
5254
https://leetcode.cn/problems/path-with-minimum-effort
5355

5456
https://leetcode.cn/problems/maximum-value-at-a-given-index-in-a-bounded-array/
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
function countPairs(nums: number[], low: number, high: number): number {
2+
return f(nums, high) - f(nums, low - 1);
3+
}
4+
5+
function f(nums: number[], x: number) {
6+
const HIGH_BIT = 14;
7+
const root = new Trie();
8+
let res = 0;
9+
10+
function add(num: number) {
11+
let cur: Trie = root;
12+
for (let k = HIGH_BIT; k >= 0; k--) {
13+
const bit = (num >> k) & 1;
14+
15+
const next = cur.son[bit] ?? new Trie();
16+
cur.son[bit] = next;
17+
cur = next;
18+
cur.sum++;
19+
}
20+
}
21+
22+
function get(num: number, x: number) {
23+
let cur: Trie = root;
24+
let sum = 0;
25+
for (let k = HIGH_BIT; k >= 0; k--) {
26+
const r = (num >> k) & 1;
27+
28+
if (((x >> k) & 1) !== 0) {
29+
const next = cur.son[r];
30+
if (next) {
31+
sum += next.sum;
32+
}
33+
const other = cur.son[r ^ 1];
34+
if (!other) {
35+
return sum;
36+
}
37+
cur = other;
38+
} else {
39+
const next = cur.son[r];
40+
if (!next) {
41+
return sum;
42+
}
43+
cur = next;
44+
}
45+
}
46+
sum += cur.sum;
47+
return sum;
48+
}
49+
50+
for (let i = 1; i < nums.length; i++) {
51+
add(nums[i - 1]);
52+
res += get(nums[i], x);
53+
}
54+
return res;
55+
}
56+
class Trie {
57+
sum: number;
58+
son: (Trie | null)[];
59+
// son[0] 表示左子树,son[1] 表示右子树
60+
constructor() {
61+
this.son = new Array<Trie | null>(2).fill(null);
62+
this.sum = 0;
63+
}
64+
}
65+
export default countPairs;

maximum-value-at-a-given-index-in-a-bounded-array/index.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@ function maxValue(n: number, index: number, maxSum: number): number {
77
right = temp;
88
}
99

10-
let upper =
11-
((left + 1) * (left + 1) - 3 * (left + 1)) / 2 +
10+
let upper = ((left + 1) * (left + 1) - 3 * (left + 1)) / 2 +
1211
left +
1312
1 +
1413
(left + 1) +
@@ -22,8 +21,7 @@ function maxValue(n: number, index: number, maxSum: number): number {
2221
return Math.floor((-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a));
2322
}
2423

25-
upper =
26-
((2 * (right + 1) - left - 1) * left) / 2 +
24+
upper = ((2 * (right + 1) - left - 1) * left) / 2 +
2725
(right + 1) +
2826
((right + 1) * (right + 1) - 3 * (right + 1)) / 2 +
2927
right +

0 commit comments

Comments
 (0)