LintCode:子数组之和

来源:互联网 发布:写编程到底什么意思 编辑:程序博客网 时间:2024/05/06 07:49

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
0 0
原创粉丝点击