LintCode:子数组之和

LintCode:子数组之和

方法一:O(n^2)复杂度:

Python

class Solution:
    """ @param nums: A list of integers @return: A list of integers includes the index of the first number and the index of the last number """
    def subarraySum(self, nums):
        # write your code here
        ans = []
        if len(nums) == 0:
            return ans

        m = len(nums)
        for i in range(m):
            sum = 0
            for j in range(i, m):
                sum += nums[j]
                if sum == 0:
                    return [i, j]

方法二:O(n)复杂度:

Python

class Solution:
    """ @param nums: A list of integers @return: A list of integers includes the index of the first number and the index of the last number """
    def subarraySum(self, nums):
        # write your code here
        m = len(nums)
        d = {0:-1}
        tmp = 0
        for i in range(m):
            tmp += nums[i]
            if tmp in d:
                return [d.get(tmp) + 1, i]
            d[tmp] = i

你可能感兴趣的:(LintCode:子数组之和)