Skip to content

Commit 702004f

Browse files
authored
Update 992-subarrays-with-k-different-integers.js
1 parent 0b5af69 commit 702004f

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

992-subarrays-with-k-different-integers.js

+14-15
Original file line numberDiff line numberDiff line change
@@ -31,22 +31,21 @@ const subarraysWithKDistinct = function(A, K) {
3131
* @return {number}
3232
*/
3333
const subarraysWithKDistinct = function (A, K) {
34-
const atMostK = (A, K) => {
35-
let left = 0,
36-
right = 0,
37-
counter = 0,
38-
count = [],
39-
result = 0
40-
while (right < A.length) {
41-
let currentR = A[right++]
42-
!count[currentR] ? ((count[currentR] = 1), counter++) : count[currentR]++
43-
while (counter > K) {
44-
let currentL = A[left++]
45-
if (--count[currentL] == 0) counter--
34+
return mostK(K) - mostK(K - 1)
35+
function mostK(num) {
36+
const m = {}, len = A.length
37+
let i = 0, j = 0, res = 0
38+
for(j = 0; j < len; j++) {
39+
if(!m[A[j]]) m[A[j]] = 0, num--
40+
m[A[j]]++
41+
while(num < 0) {
42+
m[A[i]]--
43+
if(!m[A[i]]) num++
44+
i++
4645
}
47-
result += right - left
46+
res += j - i + 1
4847
}
49-
return result
48+
return res
5049
}
51-
return atMostK(A, K) - atMostK(A, K - 1)
5250
}
51+

0 commit comments

Comments
 (0)