[Lintcode]138. Subarray Sum
138. Subarray Sum
Description
Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.
Example
Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].
Notice
There is at least one subarray that it’s sum equals to zero.
我的代码
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
s_dic = {}
s = 0
for i,item in enumerate(nums):
s += item
if s == 0:
return [0, i]
if s in s_dic:
return s_dic[s]+1, i
else:
s_dic[s] = i
别人的代码
class Solution:
def subarraySum(self, nums):
map, prefix_sum = {0: 0}, 0
for i, n in enumerate(nums):
prefix_sum += n
if prefix_sum in map:
return map[prefix_sum], i
map[prefix_sum] = i + 1
思路
此题说的应该是连续的子列,所以可以比较他们从头到某处的和,如果两处和相同,则说明中间的子列相加效果为0。
我是用dictionary实现的。别人是用map实现的。原理相同。