3254. 长度为 K 的子数组的能量值 I
为保证权益,题目请参考 3254. 长度为 K 的子数组的能量值 I(From LeetCode).
解决方案1
Python
python
from typing import List
class Solution:
def resultsArray(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
dp = [0] * n
dp[0] = 1
for i in range(1, n):
if nums[i] == nums[i - 1] + 1:
dp[i] = dp[i - 1] + 1
else:
dp[i] = 1
ans = []
for i in range(k - 1, n):
if dp[i] >= k:
ans.append(nums[i])
else:
ans.append(-1)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
解决方案2
Python
python
from typing import List
class Solution:
def resultsArray(self, nums: List[int], k: int) -> List[int]:
if k == 1:
return nums
ans = []
cur_len = 1
for i in range(1, len(nums)):
if nums[i] == nums[i - 1] + 1:
cur_len += 1
else:
cur_len = 1
if i >= k - 1:
if cur_len >= k:
ans.append(nums[i])
else:
ans.append(-1)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23