Why my simple python code has a 'Time Limit Exceeded' problem?How can I improve it?


  • 0
    H

    class NumArray(object):
    def init(self, nums):
    """
    initialize your data structure here.
    :type nums: List[int]
    """
    self.nums = nums

    def sumRange(self, i, j):
        """
        sum of elements nums[i..j], inclusive.
        :type i: int
        :type j: int
        :rtype: int
        """
        nums_list = self.nums[i:j+1]
        ret = 0
        
        ret = sum(nums_list)
                
        return ret

  • 1
    R

    it is too slow to call sum. You have to optimize your data structure

    Here is my code:

    class NumArray(object):
        def __init__(self, nums):
            """
            initialize your data structure here.
            :type nums: List[int]
            """
            self.incrSum =[0]
            for a_num in nums:
                self.incrSum.append(self.incrSum[-1]+a_num)
    
    
        def sumRange(self, i, j):
            """
            sum of elements nums[i..j], inclusive.
            :type i: int
            :type j: int
            :rtype: int
            """
            return self.incrSum[j+1]-self.incrSum[i]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.