子数组之和

子数组之和

题目:

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

至少有一个子数组的和为 0
样例
样例 1:
输入: [-3, 1, 2, -3, 4]
输出: [0,2] 或 [1,3]	
样例解释: 返回任意一段和为0的区间即可。

样例 2:
输入: [-3, 1, -4, 2, -3, 4]
输出: [1,5]

解题思路:用HashMap记录相加和与对应最后一个元素的下标,当相加和已经出现过一次后再出现则说明此时出现了和为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 List<Integer> subarraySum(int[] nums) {
        // write your code here
        List<Integer> ans = new ArrayList();
        int len = nums.length;
        int sum = 0;
        Map<Integer, Integer> map = new HashMap();
        map.put(0, -1);

        for(int i = 0; i < len; i++) {
            sum += nums[i];
            if(map.containsKey(sum)) {
                ans.add(map.get(sum) + 1);
                ans.add(i);
                break; 
            }

            map.put(sum, i);
        }

        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值