LintCode 子数组之和

题目

给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置

样例
给出 [-3, 1, 2, -3, 4],返回[0, 2]或者 [1, 3]

分析

这里用了一个技巧:将数组从第一位依次相加,记录每次的结果,如果map里面没有,就加入map里,如果有,就证明前面肯定有为0的子数组,才会出现一样的和。

代码

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) {
        // write your code here
        int len = nums.length;
       
        ArrayList<Integer> ans = new ArrayList<Integer>();
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
       
        map.put(0, -1);
       
        int sum = 0;
        for (int i = 0; i < len; i++) {
            sum += nums[i];
           
            if (map.containsKey(sum)) {
                ans.add(map.get(sum) + 1);
                ans.add(i);
                return ans;
            }
            
            map.put(sum, i);
        }
       
        return ans;
    }
}

.

推荐阅读更多精彩内容

  • 给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置注意事项There is...
    DayDayUpppppp阅读 139评论 0 0
  • 版权声明:本文为博主原创文章,未经博主允许不得转载。 难度:容易 要求: 给定一个整数数组,找到和为零的子数组。你...
    柒黍阅读 207评论 0 0
  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 2,909评论 0 4
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,436评论 0 33
  • Git图解 BY 童仲毅(geeeeeeeeek@github)这是一篇在原文基础上演绎的文章。原作者Mark L...
    奇诺小洁_a6c3阅读 190评论 0 0