leetcode
leetcode 2351 ~ 2400
特殊元素平方和

特殊元素平方和

难度:

标签:

题目描述

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?
在算法中使用 i+1 作为除数进行整除检查是因为数组的下标从 0 开始,但在数学和逻辑运算中,通常从 1 开始进行计数更为自然。因此,使用 i+1 是为了将数组下标转换为自然数序列(1, 2, 3, ...),以便正确地检查数组长度是否能够被这些自然数整除。如果使用 i 作为除数,由于数组下标从 0 开始,将会导致第一个元素用 0 作为除数,这在数学上是没有意义并且会导致运行时错误。
🦆
这种方法中,如果数组中的元素值非常大,对平方和的计算会有什么潜在的影响?是否可能导致整数溢出?
如果数组中的元素值非常大,平方这些数值可能会导致数值超过程序中整数类型的最大表达范围,这被称为整数溢出。在 Python 中,整数类型会自动转换为长整形以适应大数值,因此通常不会遇到溢出错误。但在其他一些编程语言中,如 C++ 或 Java,整数类型有固定大小,超过这个大小的数值会导致溢出错误,这可能会导致结果不准确或程序崩溃。因此,编写算法时需要考虑这一点,可能需要使用特殊的数据类型或方法来处理大数值的情况。
🦆
算法中直接使用 len(nums) 作为被除数,它是否总是等于 n?即数组的长度是否总是对应题目中的 n?
在这个算法中,使用 len(nums) 作为被除数,这里假定 len(nums) 实际上就是题目中提到的 n,即数组 nums 的长度。通常情况下,n 被用来表示数组的长度,因此这里直接使用 len(nums) 作为 n 是合理的。这意味着我们假设数组的长度就是题目中提到的 n,而无需额外的变量来专门存储这个值。
🦆
在算法实现中是否考虑了 nums 数组为空的情况?如何处理这种边界情况?
在目前的算法实现中,如果 nums 数组为空,代码中的 for 循环体将不会执行,因为 range(len(nums)) 会返回一个空范围。因此,sum 变量将保持其初始值 0,并将其作为结果返回。这种处理方式正确处理了数组为空的边界情况,因为没有元素意味着没有特殊元素,所以平方和应该是 0。

相关问题