Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7c65e0a

Browse files
[ACCEPTED][Problem 2799]Count Complete Subarrays in an Array
1 parent 55852ee commit 7c65e0a

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

‎src/medium/CountCompleteSubArraysInAnArray2799.kt

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,31 @@ package medium
33
object CountCompleteSubArraysInAnArray2799 {
44
fun countCompleteSubarrays(nums: IntArray): Int {
55
val n = nums.size
6-
val k = nums.distinct().size
6+
val distinct = nums.distinct().size
77
var result = 0
8-
var start = 0
9-
var end = 0
8+
var left = 0
9+
var right = 0
10+
val distinctMap = HashMap<Int, Int>()
1011

11-
while (start < n) {
12-
while (end < n) {
13-
val subArray = nums.copyOfRange(start, end +1)
14-
val subArrDistinct = subArray.distinct().size
15-
if (subArrDistinct == k)
16-
result++
17-
end++
12+
while (left < n) {
13+
if (left >0) {
14+
val key = nums[left -1]
15+
distinctMap[key] = distinctMap.getOrDefault(key, 0) -1
16+
if (distinctMap.getOrDefault(key, 0) == 0) {
17+
distinctMap.remove(key)
18+
}
1819
}
19-
start++
20-
end = start
20+
while (right < n && distinctMap.size < distinct) {
21+
val currentKey = nums[right]
22+
distinctMap[currentKey] = distinctMap.getOrDefault(currentKey, 0) + 1
23+
right++
24+
}
25+
if (distinctMap.size == distinct) {
26+
result += n - right + 1
27+
}
28+
left++
2129
}
2230

2331
return result
24-
2532
}
2633
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /