138. Subarray Sum

題目

https://www.lintcode.com/problem/subarray-sum/description?_from=ladder&&fromId=2

實現

  1. 定義 prefix_sum_hash 用於存放 { prefix_sum : index }
  2. 遍歷整個數組,每次計算 prefix_sum[index],判斷是否 prefix_sum[index] 是否存在於 hash 裏
    1. 如果存在那麼返回 prefix_sum_hash[prefix_sum] - 1, index
    2. 如果不存在那麼 prefix_sum_hash[prefix_sum] = i
  3. 最終返回 -1, -1

代碼

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):
        if nums is None:
            return -1, -1

        prefix_hash = { 0: -1 }
        prefix_sum = 0

        for i, num in enumerate(nums):
            prefix_sum += num

            if prefix_sum in prefix_hash:
                return prefix_hash[prefix_sum] + 1, i

            prefix_hash[prefix_sum] = i

        return -1, -1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章