LeetCode 题解工作台

子数组不同元素数目的平方和 I

给你一个下标从 0 开始的整数数组 nums 。 定义 nums 一个子数组的 不同计数 值如下: 令 nums[i..j] 表示 nums 中所有下标在 i 到 j 范围内的元素构成的子数组(满足 0 ),那么我们称子数组 nums[i..j] 中不同值的数目为 nums[i..j] 的不同计数。…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们可以枚举子数组的左端点下标 ,对于每个 ,我们在 $[i, n)$ 的范围内枚举子数组的右端点下标 ,并统计 的值,将其加入到集合 中,记 的大小为 ,那么 的不同计数为 ,将其平方后加入到答案中。 枚举结束后,返回答案即可。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的整数数组 nums 。

定义 nums 一个子数组的 不同计数 值如下:

  • 令 nums[i..j] 表示 nums 中所有下标在 ij 范围内的元素构成的子数组(满足 0 <= i <= j < nums.length ),那么我们称子数组 nums[i..j] 中不同值的数目为 nums[i..j] 的不同计数。

请你返回 nums 中所有子数组的 不同计数 的 平方 和。

由于答案可能会很大,请你将它对 109 + 7 取余 后返回。

子数组指的是一个数组里面一段连续 非空 的元素序列。

 

示例 1:

输入:nums = [1,2,1]
输出:15
解释:六个子数组分别为:
[1]: 1 个互不相同的元素。
[2]: 1 个互不相同的元素。
[1]: 1 个互不相同的元素。
[1,2]: 2 个互不相同的元素。
[2,1]: 2 个互不相同的元素。
[1,2,1]: 2 个互不相同的元素。
所有不同计数的平方和为 12 + 12 + 12 + 22 + 22 + 22 = 15 。

示例 2:

输入:nums = [2,2]
输出:3
解释:三个子数组分别为:
[2]: 1 个互不相同的元素。
[2]: 1 个互不相同的元素。
[2,2]: 1 个互不相同的元素。
所有不同计数的平方和为 12 + 12 + 12 = 3 。

 

提示:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
lightbulb

解题思路

方法一:枚举

我们可以枚举子数组的左端点下标 ii,对于每个 ii,我们在 [i,n)[i, n) 的范围内枚举子数组的右端点下标 jj,并统计 nums[j]nums[j] 的值,将其加入到集合 ss 中,记 ss 的大小为 cntcnt,那么 nums[i..j]nums[i..j] 的不同计数为 cntcnt,将其平方后加入到答案中。

枚举结束后,返回答案即可。

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

1
2
3
4
5
6
7
8
9
10
class Solution:
    def sumCounts(self, nums: List[int]) -> int:
        ans, n = 0, len(nums)
        for i in range(n):
            s = set()
            for j in range(i, n):
                s.add(nums[j])
                ans += len(s) * len(s)
        return ans
speed

复杂度分析

指标
时间complexity ranges from O(n^2) for brute-force to O(n)–O(n^2) depending on sliding window optimizations. Space complexity is O(n) for hash sets or hash maps used to track distinct elements.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Asks about counting distinct elements efficiently within subarrays.

  • question_mark

    Mentions using a set or hash map during array traversal.

  • question_mark

    Checks if you can optimize nested loops with incremental counting.

warning

常见陷阱

外企场景
  • error

    Double-counting elements when expanding subarrays without proper hash tracking.

  • error

    Forgetting to square the distinct counts before summing.

  • error

    Assuming all elements are unique without handling duplicates.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Sum of cubes of distinct element counts instead of squares.

  • arrow_right_alt

    Compute distinct counts only for subarrays of fixed length.

  • arrow_right_alt

    Count distinct element contributions modulo a large prime for large arrays.

help

常见问题

外企场景

子数组不同元素数目的平方和 I题解:数组·哈希·扫描 | LeetCode #2913 简单