【Leetcode】python - [2913] Subarrays Distinct Element Sum of Squares I 個人解法筆記

整理 LeetCode #2913 的個人解法筆記:解題思路、Time/Space Complexity 與邊界條件。

題目出處

2913. Subarrays Distinct Element Sum of Squares I

難度

easy

題目分類

Array, Hash Table, Binary Indexed Tree, Segment Tree

2026-10-15 一刷

個人範例程式碼 - 一刷 (2026/10/15)

from collections import Counter
class Solution:
    def sumCounts(self, nums: List[int]) -> int:
        ans = 0
        for i in range(len(nums)):
            seen = set()
            for j in range(i, len(nums)):
                seen.add(nums[j])
                ans += (len(seen) ** 2)


        return ans

算法說明

數學題目,結合 set 紀錄 nums[i..j] 中出現過的數字。
題目要的是窮舉所有 i..j 的可能範圍,用兩層迴圈可以搞定。

Time Complexity

O(n^2)

Space Complexity

O(n) # set 的空間

Licensed under CC BY-NC-SA 4.0
最後更新 Oct 15, 2026
使用 Hugo 建立
主題 Stack 由 Jimmy 設計