LeetCode 题解工作台
子数组不同元素数目的平方和 I
给你一个下标从 0 开始的整数数组 nums 。 定义 nums 一个子数组的 不同计数 值如下: 令 nums[i..j] 表示 nums 中所有下标在 i 到 j 范围内的元素构成的子数组(满足 0 ),那么我们称子数组 nums[i..j] 中不同值的数目为 nums[i..j] 的不同计数。…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以枚举子数组的左端点下标 ,对于每个 ,我们在 $[i, n)$ 的范围内枚举子数组的右端点下标 ,并统计 的值,将其加入到集合 中,记 的大小为 ,那么 的不同计数为 ,将其平方后加入到答案中。 枚举结束后,返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 。
定义 nums 一个子数组的 不同计数 值如下:
- 令
nums[i..j]表示nums中所有下标在i到j范围内的元素构成的子数组(满足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 <= 1001 <= nums[i] <= 100
解题思路
方法一:枚举
我们可以枚举子数组的左端点下标 ,对于每个 ,我们在 的范围内枚举子数组的右端点下标 ,并统计 的值,将其加入到集合 中,记 的大小为 ,那么 的不同计数为 ,将其平方后加入到答案中。
枚举结束后,返回答案即可。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.