LeetCode 题解工作台
和相等的子数组
给你一个下标从 0 开始的整数数组 nums ,判断是否存在 两个 长度为 2 的子数组且它们的 和 相等。注意,这两个子数组起始位置的下标必须 不相同 。 如果这样的子数组存在,请返回 true ,否则返回 false 。 子数组 是一个数组中一段连续非空的元素组成的序列。 示例 1: 输入: n…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以遍历数组 ,用哈希表 记录数组中每两个相邻元素的和,如果当前两个元素的和已经在哈希表中出现过,则返回 `true`,否则将当前两个元素的和加入哈希表中。 遍历结束后,说明没有找到满足条件的两个子数组,返回 `false`。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums ,判断是否存在 两个 长度为 2 的子数组且它们的 和 相等。注意,这两个子数组起始位置的下标必须 不相同 。
如果这样的子数组存在,请返回 true,否则返回 false 。
子数组 是一个数组中一段连续非空的元素组成的序列。
示例 1:
输入:nums = [4,2,4] 输出:true 解释:元素为 [4,2] 和 [2,4] 的子数组有相同的和 6 。
示例 2:
输入:nums = [1,2,3,4,5] 输出:false 解释:没有长度为 2 的两个子数组和相等。
示例 3:
输入:nums = [0,0,0] 输出:true 解释:子数组 [nums[0],nums[1]] 和 [nums[1],nums[2]] 的和相等,都为 0 。 注意即使子数组的元素相同,这两个子数组也视为不相同的子数组,因为它们在原数组中的起始位置不同。
提示:
2 <= nums.length <= 1000-109 <= nums[i] <= 109
解题思路
方法一:哈希表
我们可以遍历数组 ,用哈希表 记录数组中每两个相邻元素的和,如果当前两个元素的和已经在哈希表中出现过,则返回 true,否则将当前两个元素的和加入哈希表中。
遍历结束后,说明没有找到满足条件的两个子数组,返回 false。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def findSubarrays(self, nums: List[int]) -> bool:
vis = set()
for a, b in pairwise(nums):
if (x := a + b) in vis:
return True
vis.add(x)
return False
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The interviewer emphasizes subarrays of fixed length 2, which usually means scan adjacent windows instead of using nested loops.
- question_mark
They mention different starting indices, which signals that equal content is allowed as long as the windows come from separate positions.
- question_mark
A hint about counting or tracking subarray sums points straight to a hash set or hash map keyed by each pair sum.
常见陷阱
外企场景- error
Comparing subarrays themselves instead of comparing their length-2 sums adds unnecessary work and misses the actual requirement.
- error
Forgetting that overlapping windows are allowed causes wrong answers on cases like [0,0,0], where both valid windows share elements.
- error
Using an O(n^2) search over all window pairs solves small inputs but ignores the intended one-pass hash lookup pattern.
进阶变体
外企场景- arrow_right_alt
Count how many distinct length-2 sums appear more than once instead of returning a boolean.
- arrow_right_alt
Return the starting indices of the first two length-2 subarrays with equal sum rather than only true or false.
- arrow_right_alt
Generalize from size 2 to size k, where you would maintain a sliding window sum and still track repeated totals in a hash set.