Skip to content

feat: add solutions to lc problems: No.2765~2772 #1178

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion solution/1100-1199/1197.Minimum Knight Moves/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ impl Solution {
q_from.push_back((x, y));

while !q_to.is_empty() && !q_from.is_empty() {
let step = if q_to.len() < q_from.len() {
let step = if q_to.len() < q_from.len() {
Self::extend(&mut map_to, &mut map_from, &mut q_to)
} else {
Self::extend(&mut map_from, &mut map_to, &mut q_from)
Expand Down
2 changes: 1 addition & 1 deletion solution/1100-1199/1197.Minimum Knight Moves/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ impl Solution {
q_from.push_back((x, y));

while !q_to.is_empty() && !q_from.is_empty() {
let step = if q_to.len() < q_from.len() {
let step = if q_to.len() < q_from.len() {
Self::extend(&mut map_to, &mut map_from, &mut q_to)
} else {
Self::extend(&mut map_from, &mut map_to, &mut q_from)
Expand Down
167 changes: 167 additions & 0 deletions solution/2700-2799/2765.Longest Alternating Subarray/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
# [2765. 最长交替子序列](https://leetcode.cn/problems/longest-alternating-subarray)

[English Version](/solution/2700-2799/2765.Longest%20Alternating%20Subarray/README_EN.md)

## 题目描述

<!-- 这里写题目描述 -->

<p>给你一个下标从 <strong>0</strong>&nbsp;开始的整数数组&nbsp;<code>nums</code>&nbsp;。如果 <code>nums</code>&nbsp;中长度为&nbsp;<code>m</code>&nbsp;的子数组&nbsp;<code>s</code>&nbsp;满足以下条件,我们称它是一个交替子序列:</p>

<ul>
<li><code>m</code>&nbsp;大于&nbsp;<code>1</code>&nbsp;。</li>
<li><code>s<sub>1</sub> = s<sub>0</sub> + 1</code>&nbsp;。</li>
<li>下标从 0 开始的子数组&nbsp;<code>s</code>&nbsp;与数组&nbsp;<code>[s<sub>0</sub>, s<sub>1</sub>, s<sub>0</sub>, s<sub>1</sub>,...,s<sub>(m-1) % 2</sub>]</code>&nbsp;一样。也就是说,<code>s<sub>1</sub> - s<sub>0</sub> = 1</code>&nbsp;,<code>s<sub>2</sub> - s<sub>1</sub> = -1</code>&nbsp;,<code>s<sub>3</sub> - s<sub>2</sub> = 1</code>&nbsp;,<code>s<sub>4</sub> - s<sub>3</sub> = -1</code>&nbsp;,以此类推,直到&nbsp;<code>s[m - 1] - s[m - 2] = (-1)<sup>m</sup></code>&nbsp;。</li>
</ul>

<p>请你返回 <code>nums</code>&nbsp;中所有 <strong>交替</strong>&nbsp;子数组中,最长的长度,如果不存在交替子数组,请你返回 <code>-1</code>&nbsp;。</p>

<p>子数组是一个数组中一段连续 <strong>非空</strong>&nbsp;的元素序列。</p>

<p>&nbsp;</p>

<p><strong>示例 1:</strong></p>

<pre><b>输入:</b>nums = [2,3,4,3,4]
<b>输出:</b>4
<b>解释:</b>交替子数组有 [3,4] ,[3,4,3] 和 [3,4,3,4] 。最长的子数组为 [3,4,3,4] ,长度为4 。
</pre>

<p><strong>示例 2:</strong></p>

<pre><b>输入:</b>nums = [4,5,6]
<b>输出:</b>2
<strong>解释:</strong>[4,5] 和 [5,6] 是仅有的两个交替子数组。它们长度都为 2 。
</pre>

<p>&nbsp;</p>

<p><strong>提示:</strong></p>

<ul>
<li><code>2 &lt;= nums.length &lt;= 100</code></li>
<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>

## 解法

<!-- 这里可写通用的实现逻辑 -->

**方法一:枚举**

我们可以枚举子数组的左端点 $i$,对于每个 $i$,我们需要找到最长的满足条件的子数组。我们可以从 $i$ 开始向右遍历,每次遇到相邻元素差值不满足交替条件时,我们就找到了一个满足条件的子数组。我们可以用一个变量 $k$ 来记录当前元素的差值应该是 $1$ 还是 $-1$,如果当前元素的差值应该是 $-k$,那么我们就将 $k$ 取反。当我们找到一个满足条件的子数组 $nums[i..j]$ 时,我们更新答案为 $\max(ans, j - i + 1)$。

时间复杂度 $O(n^2)$,其中 $n$ 是数组的长度。我们需要枚举子数组的左端点 $i$,对于每个 $i$,我们需要 $O(n)$ 的时间来找到最长的满足条件的子数组。空间复杂度 $O(1)$。

<!-- tabs:start -->

### **Python3**

<!-- 这里可写当前语言的特殊实现逻辑 -->

```python
class Solution:
def alternatingSubarray(self, nums: List[int]) -> int:
ans, n = -1, len(nums)
for i in range(n):
k = 1
j = i
while j + 1 < n and nums[j + 1] - nums[j] == k:
j += 1
k *= -1
if j - i + 1 > 1:
ans = max(ans, j - i + 1)
return ans
```

### **Java**

<!-- 这里可写当前语言的特殊实现逻辑 -->

```java
class Solution {
public int alternatingSubarray(int[] nums) {
int ans = -1, n = nums.length;
for (int i = 0; i < n; ++i) {
int k = 1;
int 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;
}
}
```

### **C++**

```cpp
class Solution {
public:
int alternatingSubarray(vector<int>& nums) {
int ans = -1, n = nums.size();
for (int i = 0; i < n; ++i) {
int k = 1;
int j = i;
for (; j + 1 < n && nums[j + 1] - nums[j] == k; ++j) {
k *= -1;
}
if (j - i + 1 > 1) {
ans = max(ans, j - i + 1);
}
}
return ans;
}
};
```

### **Go**

```go
func alternatingSubarray(nums []int) int {
ans, n := -1, len(nums)
for i := range nums {
k := 1
j := i
for ; j+1 < n && nums[j+1]-nums[j] == k; j++ {
k *= -1
}
if t := j - i + 1; t > 1 && ans < t {
ans = t
}
}
return ans
}
```

### **TypeScript**

```ts
function alternatingSubarray(nums: number[]): number {
let ans = -1;
const n = nums.length;
for (let i = 0; i < n; ++i) {
let k = 1;
let 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;
}
```

### **...**

```

```

<!-- tabs:end -->
159 changes: 159 additions & 0 deletions solution/2700-2799/2765.Longest Alternating Subarray/README_EN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
# [2765. Longest Alternating Subarray](https://leetcode.com/problems/longest-alternating-subarray)

[中文文档](/solution/2700-2799/2765.Longest%20Alternating%20Subarray/README.md)

## Description

<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A subarray <code>s</code> of length <code>m</code> is called <strong>alternating</strong> if:</p>

<ul>
<li><code>m</code> is greater than <code>1</code>.</li>
<li><code>s<sub>1</sub> = s<sub>0</sub> + 1</code>.</li>
<li>The 0-indexed subarray <code>s</code> looks like <code>[s<sub>0</sub>, s<sub>1</sub>, s<sub>0</sub>, s<sub>1</sub>,...,s<sub>(m-1) % 2</sub>]</code>. In other words, <code>s<sub>1</sub> - s<sub>0</sub> = 1</code>, <code>s<sub>2</sub> - s<sub>1</sub> = -1</code>, <code>s<sub>3</sub> - s<sub>2</sub> = 1</code>, <code>s<sub>4</sub> - s<sub>3</sub> = -1</code>, and so on up to <code>s[m - 1] - s[m - 2] = (-1)<sup>m</sup></code>.</li>
</ul>

<p>Return <em>the maximum length of all <strong>alternating</strong> subarrays present in </em><code>nums</code> <em>or </em><code>-1</code><em> if no such subarray exists</em><em>.</em></p>

<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [2,3,4,3,4]
<strong>Output:</strong> 4
<strong>Explanation:</strong> 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.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [4,5,6]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [4,5] and [5,6] are the only two alternating subarrays. They are both of length 2.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
<li><code>2 &lt;= nums.length &lt;= 100</code></li>
<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>

## Solutions

**Solution 1: Enumeration**

We can enumerate the left endpoint $i$ of the subarray, and for each $i$, we need to find the longest subarray that satisfies the condition. We can start traversing to the right from $i$, and each time we encounter adjacent elements whose difference does not satisfy the alternating condition, we find a subarray that satisfies the condition. We can use a variable $k$ to record whether the difference of the current element should be $1$ or $-1$. If the difference of the current element should be $-k$, then we take the opposite of $k$. When we find a subarray $nums[i..j]$ that satisfies the condition, we update the answer to $\max(ans, j - i + 1)$.

The time complexity is $O(n^2)$, where $n$ is the length of the array. We need to enumerate the left endpoint $i$ of the subarray, and for each $i$, we need $O(n)$ time to find the longest subarray that satisfies the condition. The space complexity is $O(1)$.

<!-- tabs:start -->

### **Python3**

```python
class Solution:
def alternatingSubarray(self, nums: List[int]) -> int:
ans, n = -1, len(nums)
for i in range(n):
k = 1
j = i
while j + 1 < n and nums[j + 1] - nums[j] == k:
j += 1
k *= -1
if j - i + 1 > 1:
ans = max(ans, j - i + 1)
return ans
```

### **Java**

```java
class Solution {
public int alternatingSubarray(int[] nums) {
int ans = -1, n = nums.length;
for (int i = 0; i < n; ++i) {
int k = 1;
int 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;
}
}
```

### **C++**

```cpp
class Solution {
public:
int alternatingSubarray(vector<int>& nums) {
int ans = -1, n = nums.size();
for (int i = 0; i < n; ++i) {
int k = 1;
int j = i;
for (; j + 1 < n && nums[j + 1] - nums[j] == k; ++j) {
k *= -1;
}
if (j - i + 1 > 1) {
ans = max(ans, j - i + 1);
}
}
return ans;
}
};
```

### **Go**

```go
func alternatingSubarray(nums []int) int {
ans, n := -1, len(nums)
for i := range nums {
k := 1
j := i
for ; j+1 < n && nums[j+1]-nums[j] == k; j++ {
k *= -1
}
if t := j - i + 1; t > 1 && ans < t {
ans = t
}
}
return ans
}
```

### **TypeScript**

```ts
function alternatingSubarray(nums: number[]): number {
let ans = -1;
const n = nums.length;
for (let i = 0; i < n; ++i) {
let k = 1;
let 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;
}
```

### **...**

```

```

<!-- tabs:end -->
17 changes: 17 additions & 0 deletions solution/2700-2799/2765.Longest Alternating Subarray/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Solution {
public:
int alternatingSubarray(vector<int>& nums) {
int ans = -1, n = nums.size();
for (int i = 0; i < n; ++i) {
int k = 1;
int j = i;
for (; j + 1 < n && nums[j + 1] - nums[j] == k; ++j) {
k *= -1;
}
if (j - i + 1 > 1) {
ans = max(ans, j - i + 1);
}
}
return ans;
}
};
14 changes: 14 additions & 0 deletions solution/2700-2799/2765.Longest Alternating Subarray/Solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
func alternatingSubarray(nums []int) int {
ans, n := -1, len(nums)
for i := range nums {
k := 1
j := i
for ; j+1 < n && nums[j+1]-nums[j] == k; j++ {
k *= -1
}
if t := j - i + 1; t > 1 && ans < t {
ans = t
}
}
return ans
}
16 changes: 16 additions & 0 deletions solution/2700-2799/2765.Longest Alternating Subarray/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution {
public int alternatingSubarray(int[] nums) {
int ans = -1, n = nums.length;
for (int i = 0; i < n; ++i) {
int k = 1;
int 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;
}
}
Loading