【LeetCode】【Array】Running Sum of 1d Array

题目:

给定一个array nums,返回新array,每个元素为前n个元素之和(runningSum[i] = sum(nums[0]…nums[i]))。

Example 1:

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

Example 2:

Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].

Example 3:

Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]

 

Constraints:

  • 1 <= nums.length <= 1000
  • -10^6 <= nums[i] <= 10^6

【解法】

class Solution:
    def runningSum(self, nums: List[int]) -> List[int]:
        Sum = []
        temp = 0
        for i in nums:
            temp += i
            Sum.append(temp)
        return Sum
            
Runtime: 40 ms, faster than 74.57% of Python3 online submissions for Running Sum of 1d Array.
Memory Usage: 14 MB, less than 33.33% of Python3 online submissions for Running Sum of 1d Array.
【解法二】
找外援!(函数)
class Solution:
    def runningSum(self, nums: List[int]) -> List[int]:
        from itertools import accumulate
        return accumulate(nums)
Runtime: 40 ms, faster than 74.57% of Python3 online submissions for Running Sum of 1d Array.
Memory Usage: 14 MB, less than 100.00% of Python3 online submissions for Running Sum of 1d Array.

【解法三】

在原来的array里改的。

class Solution:
    def runningSum(self, nums: List[int]) -> List[int]:
        i = 1
        while i<len(nums):
            nums[i] += nums[i-1]
            i += 1
        return nums
Runtime: 68 ms, faster than 16.66% of Python3 online submissions for Running Sum of 1d Array.
Memory Usage: 14.2 MB, less than 33.33% of Python3 online submissions for Running Sum of 1d Array.

 

posted @ 2020-06-30 22:49  桃花换小鱼干好不好  阅读(186)  评论(0)    收藏  举报