特殊元素平方和
难度:
标签:
题目描述
You are given a 1-indexed integer array nums
of length n
.
An element nums[i]
of nums
is called special if i
divides n
, i.e. n % i == 0
.
Return the sum of the squares of all special elements of nums
.
Example 1:
Input: nums = [1,2,3,4] Output: 21 Explanation: There are exactly 3 special elements in nums: nums[1] since 1 divides 4, nums[2] since 2 divides 4, and nums[4] since 4 divides 4. Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[4] * nums[4] = 1 * 1 + 2 * 2 + 4 * 4 = 21.
Example 2:
Input: nums = [2,7,1,19,18,3] Output: 63 Explanation: There are exactly 4 special elements in nums: nums[1] since 1 divides 6, nums[2] since 2 divides 6, nums[3] since 3 divides 6, and nums[6] since 6 divides 6. Hence, the sum of the squares of all special elements of nums is 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.
Constraints:
1 <= nums.length == n <= 50
1 <= nums[i] <= 50
代码结果
运行时间: 27 ms, 内存: 16.0 MB
// Java Stream solution for the given problem
// Using IntStream to iterate through the array indices, filter the indices that divide the length of the array, and calculate the sum of their squares.
import java.util.stream.IntStream;
public class Solution {
public int sumOfSpecialElements(int[] nums) {
int n = nums.length;
return IntStream.rangeClosed(1, n)
.filter(i -> n % i == 0)
.map(i -> nums[i - 1] * nums[i - 1])
.sum();
}
}
解释
方法:
题解通过遍历数组 `nums` 来检查每个下标 `i`(从 0 开始)是否满足 `n % (i+1) == 0` 的条件。这里的 `i+1` 表示从 1 开始的下标。如果满足条件,说明 `nums[i]` 是特殊元素,将其平方后加入到累加器 `sum` 中。循环结束后返回 `sum`,即所有特殊元素平方和。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么在算法中使用 i+1 作为除数进行整除检查,而不是直接使用 i?
▷🦆
这种方法中,如果数组中的元素值非常大,对平方和的计算会有什么潜在的影响?是否可能导致整数溢出?
▷🦆
算法中直接使用 len(nums) 作为被除数,它是否总是等于 n?即数组的长度是否总是对应题目中的 n?
▷🦆
在算法实现中是否考虑了 nums 数组为空的情况?如何处理这种边界情况?
▷