Lintcode:subarray Sum Problem Solving report

Source: Internet
Author: User
Tags lintcode

Subarray Sum

Original title Link: http://lintcode.com/zh-cn/problem/subarray-sum/#

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 last number of the index.

Sample Example

Given [ -3, 1, 2, -3, 4], return [0, 2] or [1, 3].

label Expand

Solution 1:

We have an O (N) solution. Use map to record the value of index, sum. When the sum of two index is encountered at the same time, the representation from index1+1 to Index2 is a solution.

Note: Add an index =-1 as the virtual node. So that we can record the solution of index1 = 0.

Space complexity: O (N)

1  Public classSolution {2     /**3      * @paramnums:a List of integers4      * @return: A list of integers includes the index of the first number5 * The index of the last number6      */7      PublicArraylist<integer> Subarraysum (int[] nums) {8         //Write your code here9         Ten         intLen =nums.length; One          Aarraylist<integer> ret =NewArraylist<integer>(); -          -Hashmap<integer, integer> map =NewHashmap<integer, integer>(); the          -         //We Set the index-1 sum to being 0 to let us more convient to count. -Map.put (0,-1); -          +         intsum = 0; -          for(inti = 0; i < Len; i++) { +Sum + =Nums[i]; A              at             if(Map.containskey (sum)) { -                 //For Example: -                 //-3 1 2-3 4 -                 //sum:0 -3-2 0-3 1 -                 //Then we got the solution is:0-2 -Ret.add (Map.get (sum) + 1); in Ret.add (i); -                 returnret; to             } +              -             //Store the Key:value of Sum:index. the map.put (sum, i); *         } $         Panax Notoginseng         returnret; -     } the}
View Code

GITHUB:

Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/array/SubarraySum.java

Lintcode:subarray Sum Problem Solving report

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.