当前位置: 资讯 >

LeetCode 2765. Longest Alternating Subarray

来源:哔哩哔哩 发表日期:2023-07-09 08:15:28

You are given a 0-indexed integer array nums. A subarray sof length mis called alternating if:


(资料图)

mis greater than 1.

s1 = s0 + 1.

The 0-indexed subarray slooks like [s0, s1, s0, s1,...,s(m-1) % 2]. In other words, s1 - s0 = 1s2 - s1 = -1s3 - s2 = 1s4 - s3 = -1, and so on up to s[m - 1] - s[m - 2] = (-1)m.

Return the maximum length of all alternating subarrays present in numsor -1if no such subarray exists.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [2,3,4,3,4]

Output: 4

Explanation: The alternating subarrays are [3, 4], [3, 4, 3], and [3, 4, 3, 4]. The longest of these is [3,4,3,4], which is of length 4.

Example 2:

Input: nums = [4,5,6]

Output: 2

Explanation: [4,5] and [5,6] are the only two alternating subarrays. They are both of length 2.

Constraints:

2 <= <= 100

1 <= nums[i] <= 104

-------------------------------

解:先判断第一项是否符合,如果不符合,直接返回,然后去遍历每个元素是否跟它后面第2个数字是否一致即可。这个函数写好后,再去依次遍历,判断是否符合。下面是代码;

Runtime: 37 ms, faster than % of Java online submissions for Longest Alternating Subarray.

Memory Usage:  MB, less than % of Java online submissions for Longest Alternating Subarray.

x
推荐阅读 更多