kt: add «3097. Shortest Subarray With OR at Least K II»
URL: https://leetcode.com/problems/shortest-subarray-with-or-at-least-k-ii/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
c5d0cc0c89
commit
97b79b8025
1 changed files with 54 additions and 0 deletions
54
kt/shortest-subarray-with-or-at-least-k-ii.kt
Normal file
54
kt/shortest-subarray-with-or-at-least-k-ii.kt
Normal file
|
@ -0,0 +1,54 @@
|
|||
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
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue