Skip to content
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

feat: add solutions to lc problem: No.0325 #4281

Merged
merged 1 commit into from
Mar 22, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ tags:

<pre>
<strong>输入: </strong><em>nums</em> = <code>[1,-1,5,-2,3]</code>, <em>k</em> = <code>3</code>
<strong>输出: </strong>4
<strong>输出: </strong>4
<strong>解释: </strong>子数组 <code>[1, -1, 5, -2]</code> 和等于 3,且长度最长。
</pre>

Expand Down Expand Up @@ -55,13 +55,13 @@ tags:

### 方法一:哈希表 + 前缀和

我们可以用一个哈希表 $d$ 记录数组 $nums$ 中每个前缀和第一次出现的下标,初始时 $d[0] = -1$。另外定义一个变量 $s$ 记录前缀和。
我们可以用一个哈希表 $\textit{d}$ 记录数组 $\textit{nums}$ 中每个前缀和第一次出现的下标,初始时 $\textit{d}[0] = -1$。另外定义一个变量 $\textit{s}$ 记录前缀和。

接下来,遍历数组 $nums$,对于当前遍历到的数字 $nums[i]$,我们更新前缀和 $s = s + nums[i]$,如果 $s-k$ 在哈希表 $d$ 中存在,不妨记 $j = d[s - k]$,那么以 $nums[i]$ 结尾的符合条件的子数组的长度为 $i - j$,我们使用一个变量 $ans$ 来维护最长的符合条件的子数组的长度。然后,如果 $s$ 在哈希表中不存在,我们记录 $s$ 和对应的下标 $i$,即 $d[s] = i$,否则我们不更新 $d[s]$。需要注意的是,可能会有多个位置 $i$ 都满足 $s$ 的值,因此我们只记录最小的 $i$,这样就能保证子数组的长度最长。
接下来,遍历数组 $\textit{nums}$,对于当前遍历到的数字 $\textit{nums}[i]$,我们更新前缀和 $\textit{s} = \textit{s} + \textit{nums}[i]$,如果 $\textit{s}-k$ 在哈希表 $\textit{d}$ 中存在,不妨记 $j = \textit{d}[\textit{s} - k]$,那么以 $\textit{nums}[i]$ 结尾的符合条件的子数组的长度为 $i - j$,我们使用一个变量 $\textit{ans}$ 来维护最长的符合条件的子数组的长度。然后,如果 $\textit{s}$ 在哈希表中不存在,我们记录 $\textit{s}$ 和对应的下标 $i$,即 $\textit{d}[\textit{s}] = i$,否则我们不更新 $\textit{d}[\textit{s}]$。需要注意的是,可能会有多个位置 $i$ 都满足 $\textit{s}$ 的值,因此我们只记录最小的 $i$,这样就能保证子数组的长度最长。

遍历结束之后,我们返回 $ans$ 即可。
遍历结束之后,我们返回 $\textit{ans}$ 即可。

时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $\textit{nums}$ 的长度。

<!-- tabs:start -->

Expand Down Expand Up @@ -163,6 +163,80 @@ function maxSubArrayLen(nums: number[], k: number): number {
}
```

#### Rust

```rust
use std::collections::HashMap;

impl Solution {
pub fn max_sub_array_len(nums: Vec<i32>, k: i32) -> i32 {
let mut d = HashMap::new();
d.insert(0, -1);
let mut ans = 0;
let mut s = 0;

for (i, &x) in nums.iter().enumerate() {
s += x;
if let Some(&j) = d.get(&(s - k)) {
ans = ans.max((i as i32) - j);
}
d.entry(s).or_insert(i as i32);
}

ans
}
}
```

#### JavaScript

```js
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var maxSubArrayLen = function (nums, k) {
const d = new Map();
d.set(0, -1);
let ans = 0;
let s = 0;
for (let i = 0; i < nums.length; ++i) {
s += nums[i];
if (d.has(s - k)) {
ans = Math.max(ans, i - d.get(s - k));
}
if (!d.has(s)) {
d.set(s, i);
}
}
return ans;
};
```

#### C#

```cs
public class Solution {
public int MaxSubArrayLen(int[] nums, int k) {
var d = new Dictionary<int, int>();
d[0] = -1;
int ans = 0;
int s = 0;
for (int i = 0; i < nums.Length; i++) {
s += nums[i];
if (d.ContainsKey(s - k)) {
ans = Math.Max(ans, i - d[s - k]);
}
if (!d.ContainsKey(s)) {
d[s] = i;
}
}
return ans;
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,15 @@ tags:

<!-- solution:start -->

### Solution 1
### Solution 1: Hash Table + Prefix Sum

We can use a hash table $\textit{d}$ to record the first occurrence index of each prefix sum in the array $\textit{nums}$, initializing $\textit{d}[0] = -1$. Additionally, we define a variable $\textit{s}$ to keep track of the current prefix sum.

Next, we iterate through the array $\textit{nums}$. For the current number $\textit{nums}[i]$, we update the prefix sum $\textit{s} = \textit{s} + \textit{nums}[i]$. If $\textit{s} - k$ exists in the hash table $\textit{d}$, let $\textit{j} = \textit{d}[\textit{s} - k]$, then the length of the subarray that ends at $\textit{nums}[i]$ and satisfies the condition is $i - j$. We use a variable $\textit{ans}$ to maintain the length of the longest subarray that satisfies the condition. After that, if $\textit{s}$ does not exist in the hash table, we record $\textit{s}$ and its corresponding index $i$ by setting $\textit{d}[\textit{s}] = i$. Otherwise, we do not update $\textit{d}[\textit{s}]$. It is important to note that there may be multiple positions $i$ with the same value of $\textit{s}$, so we only record the smallest $i$ to ensure the subarray length is the longest.

After the iteration ends, we return $\textit{ans}$.

The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$.

<!-- tabs:start -->

Expand Down Expand Up @@ -154,6 +162,80 @@ function maxSubArrayLen(nums: number[], k: number): number {
}
```

#### Rust

```rust
use std::collections::HashMap;

impl Solution {
pub fn max_sub_array_len(nums: Vec<i32>, k: i32) -> i32 {
let mut d = HashMap::new();
d.insert(0, -1);
let mut ans = 0;
let mut s = 0;

for (i, &x) in nums.iter().enumerate() {
s += x;
if let Some(&j) = d.get(&(s - k)) {
ans = ans.max((i as i32) - j);
}
d.entry(s).or_insert(i as i32);
}

ans
}
}
```

#### JavaScript

```js
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var maxSubArrayLen = function (nums, k) {
const d = new Map();
d.set(0, -1);
let ans = 0;
let s = 0;
for (let i = 0; i < nums.length; ++i) {
s += nums[i];
if (d.has(s - k)) {
ans = Math.max(ans, i - d.get(s - k));
}
if (!d.has(s)) {
d.set(s, i);
}
}
return ans;
};
```

#### C#

```cs
public class Solution {
public int MaxSubArrayLen(int[] nums, int k) {
var d = new Dictionary<int, int>();
d[0] = -1;
int ans = 0;
int s = 0;
for (int i = 0; i < nums.Length; i++) {
s += nums[i];
if (d.ContainsKey(s - k)) {
ans = Math.Max(ans, i - d[s - k]);
}
if (!d.ContainsKey(s)) {
d[s] = i;
}
}
return ans;
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
public class Solution {
public int MaxSubArrayLen(int[] nums, int k) {
var d = new Dictionary<int, int>();
d[0] = -1;
int ans = 0;
int s = 0;
for (int i = 0; i < nums.Length; i++) {
s += nums[i];
if (d.ContainsKey(s - k)) {
ans = Math.Max(ans, i - d[s - k]);
}
if (!d.ContainsKey(s)) {
d[s] = i;
}
}
return ans;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var maxSubArrayLen = function (nums, k) {
const d = new Map();
d.set(0, -1);
let ans = 0;
let s = 0;
for (let i = 0; i < nums.length; ++i) {
s += nums[i];
if (d.has(s - k)) {
ans = Math.max(ans, i - d.get(s - k));
}
if (!d.has(s)) {
d.set(s, i);
}
}
return ans;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use std::collections::HashMap;

impl Solution {
pub fn max_sub_array_len(nums: Vec<i32>, k: i32) -> i32 {
let mut d = HashMap::new();
d.insert(0, -1);
let mut ans = 0;
let mut s = 0;

for (i, &x) in nums.iter().enumerate() {
s += x;
if let Some(&j) = d.get(&(s - k)) {
ans = ans.max((i as i32) - j);
}
d.entry(s).or_insert(i as i32);
}

ans
}
}