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].
Note
There is at least one subarray that it’s sum equals to zero.
classSolution:""" @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 """defsubarraySum(self,nums):# write your code hereresult=[]ifnums==Noneorlen(nums)==0:returnresultforiinrange(len(nums)):# [1,2,3,0] => [3,3] is correctifnums[i]==0:return[i,i]sum=nums[i]forjinrange(i+1,len(nums)):ifsum+nums[j]==0:result.append(i)result.append(j)returnresultelse:sum+=nums[j]returnresult
Hash table: O(N)
Hash Table: {[sum: index+1]}
You calculate the sum of substrings and maintain the hash table, if you find the sum appear again, you find the substring
For example: [hash-table[sum],x,x,x,i] then[x,x,x,i] is the string
Consider when sum==0, we have to initialize the hash-table with {[0:0]}
classSolution:""" @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 """defsubarraySum(self,nums):# write your code here# hash_map: {sum: index}hash_map=dict()hash_map[0]=0result=[]ifnums==Noneorlen(nums)==0:returnresultsum=0foriinrange(len(nums)):# case <x, x, x, 0, x, x>ifnums[i]==0:result.append(i)result.append(i)returnresultsum+=nums[i]# if you find sum again# <hash_map[sum],x,x,x,i> is the substring you are looking forif(hash_map.has_key(sum)):result.append(hash_map[sum])result.append(i)returnresultelse:hash_map[sum]=i+1returnresult