题目的意思就是想找到最长的 +1,-1,+1,-1… 的子数组的长度,硬找呗
class Solution:
def alternatingSubarray(self, nums: List[int]) -> int:
st = 0
ans = 1
while st < len(nums):
index = st + 1
while index < len(nums):
if (index - st) % 2 == 0:
if nums[index] != nums[st]:
break
else:
if nums[index] != nums[st] + 1:
break
index += 1
ans = max(ans, index - st)
st = max(st + 1, index - 1)
return ans if ans != 1 else -1