Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit a08249c

Browse files
authoredApr 28, 2024
Create 3134-find-the-median-of-the-uniqueness-array.js
1 parent df72253 commit a08249c

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var medianOfUniquenessArray = function (nums) {
6+
let low = 1
7+
let high = nums.length
8+
let n = nums.length
9+
10+
while (low < high) {
11+
let mid = low + Math.floor((high - low) / 2)
12+
if (countDistinct(nums, mid) >= Math.floor(((n * (n + 1)) / 2 + 1) / 2)) {
13+
high = mid
14+
} else {
15+
low = mid + 1
16+
}
17+
}
18+
19+
if (
20+
countDistinct(nums, low - 1) === Math.floor(((n * (n + 1)) / 2 + 1) / 2)
21+
) {
22+
return low - 1
23+
}
24+
return low
25+
}
26+
27+
function countDistinct(nums, k) {
28+
let occurrences = new Map()
29+
let left = 0
30+
let count = 0
31+
let result = 0
32+
33+
for (let right = 0; right < nums.length; right++) {
34+
occurrences.set(nums[right], (occurrences.get(nums[right]) || 0) + 1)
35+
if (occurrences.get(nums[right]) === 1) {
36+
count++
37+
}
38+
while (count > k) {
39+
occurrences.set(nums[left], occurrences.get(nums[left]) - 1)
40+
if (occurrences.get(nums[left]) === 0) {
41+
count--
42+
}
43+
left++
44+
}
45+
result += right - left + 1
46+
}
47+
return result
48+
}
49+
50+
function force(nums) {
51+
let l = []
52+
for (let i = 0; i < nums.length; i++) {
53+
let set = new Set()
54+
for (let j = i; j < nums.length; j++) {
55+
set.add(nums[j])
56+
l.push(set.size)
57+
}
58+
}
59+
l.sort((a, b) => a - b)
60+
return l[Math.floor(l.length / 2)]
61+
}

0 commit comments

Comments
 (0)
Please sign in to comment.