-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2080-range-frequency-queries.js
More file actions
72 lines (65 loc) · 1.9 KB
/
2080-range-frequency-queries.js
File metadata and controls
72 lines (65 loc) · 1.9 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* 2080. Range Frequency Queries
* https://leetcode.com/problems/range-frequency-queries/
* Difficulty: Medium
*
* Design a data structure to find the frequency of a given value in a given subarray.
*
* The frequency of a value in a subarray is the number of occurrences of that value in
* the subarray.
*
* Implement the RangeFreqQuery class:
* - RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed
* integer array arr.
* - int query(int left, int right, int value) Returns the frequency of value in the subarray
* arr[left...right].
* - A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes
* the subarray that contains the elements of nums between indices left and right (inclusive).
*/
/**
* @param {number[]} arr
*/
var RangeFreqQuery = function(arr) {
this.frequencyMap = new Map();
for (let i = 0; i < arr.length; i++) {
if (!this.frequencyMap.has(arr[i])) {
this.frequencyMap.set(arr[i], []);
}
this.frequencyMap.get(arr[i]).push(i);
}
};
/**
* @param {number} left
* @param {number} right
* @param {number} value
* @return {number}
*/
RangeFreqQuery.prototype.query = function(left, right, value) {
if (!this.frequencyMap.has(value)) return 0;
const indices = this.frequencyMap.get(value);
let start = 0;
let end = indices.length - 1;
let leftBound = -1;
let rightBound = -1;
while (start <= end) {
const mid = Math.floor((start + end) / 2);
if (indices[mid] >= left) {
leftBound = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
start = 0;
end = indices.length - 1;
while (start <= end) {
const mid = Math.floor((start + end) / 2);
if (indices[mid] <= right) {
rightBound = mid;
start = mid + 1;
} else {
end = mid - 1;
}
}
return leftBound === -1 || rightBound === -1 ? 0 : rightBound - leftBound + 1;
};