2778. Sum of Squares of Special Elements

LeetCode 力扣

1. Description

Treat nums, an integer array of length n, as indexed from 1 through n.
An element is special when its index is a divisor of n. Compute the sum obtained by squaring each special element and adding the results.

2. Example

Example 1

Input: nums = [1,2,3,4]
Output: 21
Explanation: The qualifying positions are 1, 2, and 4, giving $1^2 + 2^2 + 4^2 = 21$.

Example 2

Input: nums = [2,7,1,19,18,3]
Output: 63
Explanation: The qualifying positions are 1, 2, 3, and 6, giving $2^2 + 7^2 + 1^2 + 3^2 = 63$.

3. Constraints

  • 1 <= nums.length == n <= 50
  • 1 <= nums[i] <= 50

4. Solutions

Enumeration

n = nums.size()
Time complexity: O(n)
Space complexity: O(1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
public:
    int sumOfSquares(const vector<int> &nums) {
        int sum = 0;
        for (int i = 0, n = nums.size(); i < n; ++i) {
            if (n % (i + 1) == 0) {
                sum += nums[i] * nums[i];
            }
        }

        return sum;
    }
};
comments powered by Disqus