lintcode_138--Sub-array and zero

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.