Subarray Sum

来源:互联网 发布:手机淘宝批量退款 编辑:程序博客网 时间:2024/04/30 14:50

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.

 Notice

There is at least one subarray that it's sum equals to zero.

Example

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


public 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     */    public ArrayList<Integer> subarraySum(int[] nums) {        int l = nums.length;        ArrayList<Integer> list = new ArrayList<Integer>();        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();        map.put(0, -1);//for the case like [1, -1]        int sum = 0;        for(int i = 0; i < l; i++) {            sum += nums[i];            if(map.containsKey(sum)) {                list.add(map.get(sum) + 1);                list.add(i);                return list;            }            map.put(sum, i);        }        return list;    }}/**推荐解法:The idea is based on the prefix sum: Iterate through the array and for every element array【i】, calculate sum of elements form 0 to i (this can simply be done as sum += arr【i】). If the current sum has been seen before, then there is a zero sum array, the start and end index are returned.用HashMap: O(N)时间,但是more memory, 大case会MLE**/




0 0
原创粉丝点击