LeetCode 题解工作台
特殊元素平方和
给你一个下标从 1 开始、长度为 n 的整数数组 nums 。 对 nums 中的元素 nums[i] 而言,如果 n 能够被 i 整除,即 n % i == 0 ,则认为 nums[i] 是一个 特殊元素 。 返回 nums 中所有 特殊元素 的 平方和 。 示例 1: 输入: nums = [1…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·结合·enumeration
答案摘要
我们可以枚举数组中的每个元素,判断其是否为特殊元素,如果是则将其平方加入答案中。 时间复杂度 ,其中 是数组的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·enumeration 题型思路
题目描述
给你一个下标从 1 开始、长度为 n 的整数数组 nums 。
对 nums 中的元素 nums[i] 而言,如果 n 能够被 i 整除,即 n % i == 0 ,则认为 nums[i] 是一个 特殊元素 。
返回 nums 中所有 特殊元素 的 平方和 。
示例 1:
输入:nums = [1,2,3,4] 输出:21 解释:nums 中共有 3 个特殊元素:nums[1],因为 4 被 1 整除;nums[2],因为 4 被 2 整除;以及 nums[4],因为 4 被 4 整除。 因此,nums 中所有特殊元素的平方和等于 nums[1] * nums[1] + nums[2] * nums[2] + nums[4] * nums[4] = 1 * 1 + 2 * 2 + 4 * 4 = 21 。
示例 2:
输入:nums = [2,7,1,19,18,3] 输出:63 解释:nums 中共有 4 个特殊元素:nums[1],因为 6 被 1 整除;nums[2] ,因为 6 被 2 整除;nums[3],因为 6 被 3 整除;以及 nums[6],因为 6 被 6 整除。 因此,nums 中所有特殊元素的平方和等于 nums[1] * nums[1] + nums[2] * nums[2] + nums[3] * nums[3] + nums[6] * nums[6] = 2 * 2 + 7 * 7 + 1 * 1 + 3 * 3 = 63 。
提示:
1 <= nums.length == n <= 501 <= nums[i] <= 50
解题思路
方法一:枚举
我们可以枚举数组中的每个元素,判断其是否为特殊元素,如果是则将其平方加入答案中。
时间复杂度 ,其中 是数组的长度。空间复杂度 。
class Solution:
def sumOfSquares(self, nums: List[int]) -> int:
n = len(nums)
return sum(x * x for i, x in enumerate(nums, 1) if n % i == 0)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each index is checked once. Space complexity is O(1) since only a running sum is stored, not the list of special elements. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Are you correctly identifying 1-indexed elements as special using n % i?
- question_mark
Can you explain why iterating from 1 to n covers all potential special elements?
- question_mark
Do you handle arrays where multiple indices divide n without missing any special elements?
常见陷阱
外企场景- error
Using 0-based indexing incorrectly instead of 1-based indexing for special element checks.
- error
Squaring the wrong elements by misaligning array indices with the divisor check.
- error
Forgetting that n itself may be a divisor and nums[n] must be included if special.
进阶变体
外企场景- arrow_right_alt
Compute the product of all special elements instead of sum of squares.
- arrow_right_alt
Return the sum of cubes of special elements for a modified numerical pattern.
- arrow_right_alt
Count how many elements are special instead of summing their squares.