1. 程式人生 > 其它 >LeetCode 1588 Sum Of All Odd Length Subarrays Writeup

LeetCode 1588 Sum Of All Odd Length Subarrays Writeup

技術標籤:LeetCodePracticeleetcode資料結構演算法

所有奇數長度子陣列的和

原題

from typing import List

class Solution:
    def sumOddLengthSubarrays(self, arr: List[int]) -> int:
        sums = 0
        for i in range(1,len(arr)+1,2):     #步長從1到arr長度加一,左閉右開
            j = 0
            while i+j <= len(arr):
                sums +=
sum(arr[j:j+i]) #逐個累加子陣列的和 j += 1 return sums

複雜度分析

  1. 時間複雜度:大概是O(n ^ 2),切片的複雜度不太清楚
  2. 空間複雜度:大概是O(n)