-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnode.js
More file actions
36 lines (27 loc) · 821 Bytes
/
node.js
File metadata and controls
36 lines (27 loc) · 821 Bytes
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
function majorityElement(nums) {
return majorityElementRec(nums, 0, nums.length - 1);
}
function majorityElementRec(nums, low, high) {
if (low === high) {
return nums[low];
}
let mid = Math.floor((high - low) / 2) + low;
let left = majorityElementRec(nums, low, mid);
let right = majorityElementRec(nums, mid + 1, high);
if (left === right) return left;
let leftCount = countInRange(nums, left, low, high);
let rightCount = countInRange(nums, right, low, high);
// console.log(leftCount, rightCount);
return leftCount > rightCount ? left : right;
}
function countInRange(nums, num, low, high) {
let count = 0;
for (let i = low; i <= high; i++) {
if (nums[i] === num) {
count++;
}
}
return count;
}
let arr = [2, 2, 3, 3, 3, 3, 2]
console.log(majorityElement(arr));