Title:
Given an array of integers, locate and zero the sub-array. Your code should return the starting and ending positions of the subarray that meet the requirements.
Sample Example Given [-3, 1, 2,-3, 4], return [0, 2] or [1, 3].
Problem Solving Ideas:
The prefix of the array is evaluated in turn and the following actions are performed:
Assuming that the current position is I, find the prefix of the position before I and, if there is a J position, so that the J position is prefixed with the prefix and equal to the I position.
If so, then the number of intervals between J and I is 0.
Until the complete array is traversed.
Time complexity O (n), spatial complexity O (n).
Implementation code:
Class Solution {public: /** * @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 * /vector<int> subarraysum (vector<int> ; Nums) { //write your code here int sum = 0; vector<int> ret; Unordered_map<int, int> map; Map[0] =-1; for (int i=0; i<nums.size (); i++) { sum + = nums[i]; if (Map.find (sum)! = Map.end ()) { ret.push_back (Map[sum] + 1); Ret.push_back (i); return ret; } Map[sum] = i; } return ret; }};
lintcode_138--Sub-array and zero