-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy path1157-online-majority-element-in-subarray.js
77 lines (70 loc) · 2.19 KB
/
1157-online-majority-element-in-subarray.js
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
73
74
75
76
77
/**
* 1157. Online Majority Element In Subarray
* https://leetcode.com/problems/online-majority-element-in-subarray/
* Difficulty: Hard
*
* Design a data structure that efficiently finds the majority element of a given subarray.
*
* The majority element of a subarray is an element that occurs threshold times or more in
* the subarray.
*
* Implementing the MajorityChecker class:
* - MajorityChecker(int[] arr) Initializes the instance of the class with the given array arr.
* - int query(int left, int right, int threshold) returns the element in the subarray
* arr[left...right] that occurs at least threshold times, or -1 if no such element exists.
*/
/**
* @param {number[]} arr
*/
var MajorityChecker = function(arr) {
this.positionMap = new Map();
this.array = arr;
for (let i = 0; i < arr.length; i++) {
const positions = this.positionMap.get(arr[i]) || [];
positions.push(i);
this.positionMap.set(arr[i], positions);
}
};
/**
* @param {number} left
* @param {number} right
* @param {number} threshold
* @return {number}
*/
MajorityChecker.prototype.query = function(left, right, threshold) {
const maxAttempts = 20;
const rangeLength = right - left + 1;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const candidate = this.array[left + Math.floor(Math.random() * rangeLength)];
const positions = this.positionMap.get(candidate);
const count = countInRange(positions, left, right);
if (count >= threshold) return candidate;
if (count + rangeLength - count < threshold) return -1;
}
return -1;
};
function countInRange(positions, left, right) {
const leftIndex = lowerBound(positions, left);
const rightIndex = upperBound(positions, right);
return rightIndex - leftIndex;
}
function lowerBound(arr, target) {
let start = 0;
let end = arr.length;
while (start < end) {
const mid = Math.floor((start + end) / 2);
if (arr[mid] < target) start = mid + 1;
else end = mid;
}
return start;
}
function upperBound(arr, target) {
let start = 0;
let end = arr.length;
while (start < end) {
const mid = Math.floor((start + end) / 2);
if (arr[mid] <= target) start = mid + 1;
else end = mid;
}
return start;
}