作者dont (dont)
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Sun Nov 10 11:03:45 2024
3097. Shortest Subarray With OR at Least K II
## 思路
sliding window紀錄每個bit的個數
檢查or的val, 如果val >= k 就更新window left
## Code
```python
class Solution:
def minimumSubarrayLength(self, nums: List[int], k: int) -> int:
if k == 0:
return 1
n = len(nums)
res = float('inf')
count = [0] * 32
left = 0
for right in range(n):
val = 0
for i in range(32):
if nums[right] & (1 << i):
count[i] += 1
if count[i]:
val |= (1 << i)
while val >= k:
res = min(res, right - left + 1)
val = 0
for i in range(32):
if nums[left] & (1 << i):
count[i] -= 1
if count[i]:
val |= (1 << i)
left += 1
return -1 if res == float('inf') else res
```
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 185.213.82.154 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1731207827.A.174.html