LeetCode 题解工作台

和相等的子数组

给你一个下标从 0 开始的整数数组 nums ,判断是否存在 两个 长度为 2 的子数组且它们的 和 相等。注意,这两个子数组起始位置的下标必须 不相同 。 如果这样的子数组存在,请返回 true ,否则返回 false 。 子数组 是一个数组中一段连续非空的元素组成的序列。 示例 1: 输入: n…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们可以遍历数组 ,用哈希表 记录数组中每两个相邻元素的和,如果当前两个元素的和已经在哈希表中出现过,则返回 `true`,否则将当前两个元素的和加入哈希表中。 遍历结束后,说明没有找到满足条件的两个子数组,返回 `false`。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 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
lightbulb

解题思路

方法一:哈希表

我们可以遍历数组 numsnums,用哈希表 visvis 记录数组中每两个相邻元素的和,如果当前两个元素的和已经在哈希表中出现过,则返回 true,否则将当前两个元素的和加入哈希表中。

遍历结束后,说明没有找到满足条件的两个子数组,返回 false

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 numsnums 的长度。

1
2
3
4
5
6
7
8
9
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

和相等的子数组题解:数组·哈希·扫描 | LeetCode #2395 简单