LC.P2765[最长交替子数组] 方法一:枚举123456789101112131415class Solution { public int alternatingSubarray(int[] nums) { int ans = -1, n = nums.length; for (int i = 0; i < n; ++i) { int k = 1, j = i; for ( ; j + 1 < n && nums[j + 1] - nums[j] == k; ++j) { k *= -1; } if (j - i + 1 > 1) { ans = Math.max(ans, j - i + 1); } } return ans; }} 时间复杂度:$O(n^2)$ 空间复杂度:$O(1)$