55 lines
1.3 KiB
Kotlin
55 lines
1.3 KiB
Kotlin
|
class Solution {
|
||
|
private data class Window(val bits: IntArray, var left: Int) {
|
||
|
fun updateBits(
|
||
|
number: Int,
|
||
|
d: Int,
|
||
|
) = bits.indices
|
||
|
.filter { number.shr(it).and(1) != 0 }
|
||
|
.forEach {
|
||
|
bits[it] += d
|
||
|
}
|
||
|
|
||
|
fun toInt(): Int =
|
||
|
bits
|
||
|
.mapIndexed { index, it ->
|
||
|
when {
|
||
|
it != 0 -> 1.shl(index)
|
||
|
else -> 0
|
||
|
}
|
||
|
}
|
||
|
.reduce(Int::or)
|
||
|
|
||
|
fun update(
|
||
|
nums: IntArray,
|
||
|
k: Int,
|
||
|
right: Int,
|
||
|
): Int {
|
||
|
updateBits(nums[right], 1)
|
||
|
|
||
|
var minLength = Int.MAX_VALUE
|
||
|
while (left <= right && toInt() >= k) {
|
||
|
minLength = listOf(minLength, right - left + 1).min()
|
||
|
|
||
|
updateBits(nums[left], -1)
|
||
|
left += 1
|
||
|
}
|
||
|
|
||
|
return minLength
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fun minimumSubarrayLength(
|
||
|
nums: IntArray,
|
||
|
k: Int,
|
||
|
): Int {
|
||
|
val window = Window(IntArray(32), 0)
|
||
|
|
||
|
return nums.indices
|
||
|
.map {
|
||
|
window.update(nums, k, it)
|
||
|
}
|
||
|
.filter { it < Int.MAX_VALUE }
|
||
|
.minOrNull() ?: -1
|
||
|
}
|
||
|
}
|