【两次过】Lintcode 138. 子数组之和

本文介绍了一种高效算法,用于在整数数组中找到和为零的子数组,通过使用HashMap存储累计和及其对应的下标,实现O(n)的时间复杂度。文章提供了详细的解题思路和代码实现。

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

样例

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

注意事项

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


解题思路1:

常规思路是循环扫描,时间复杂度O(n^2),不可取

注意[0]的情况,以及含有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
        if(nums == null || nums.length == 0)
            return null;
        
        List<Integer> res = new ArrayList<>();
        
        if(nums.length == 1 && nums[0] == 0){
            res.add(0);
            res.add(0);
            
            return res;
        }
        
        for(int i=0; i<nums.length; i++){
            int sum = nums[i];
            int first = i;
            int end = i;
            
            for(int j=i+1; j<nums.length; j++){
                if(sum == 0){
                    res.add(first);
                    res.add(end);
                    
                    return res;
                }
                
                sum += nums[j];
                end = j;
                
                if(sum == 0){
                    res.add(first);
                    res.add(end);
                    
                    return res;
                }
            } 
        }
        
        return res;
    }
}

解题思路2:

如果有子数组[i,j]和为零,则表示前i个元素之和(不包括i) == 前j个元素之和(包括j)

用HashMap存储,key表示依次的和,value表示当前和的下标

当碰到相同和的时候则代表找到和为零的子数组

注意初始化:map.put(0, -1),这样可以记录下标==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
        if(nums == null || nums.length == 0)
            return null;
        
        List<Integer> res = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        
        int sum = 0;
        for(int i=0; i<nums.length; i++){
            sum += nums[i];
            
            if(map.containsKey(sum)){
                res.add(map.get(sum) + 1);
                res.add(i);
                break;
            }else{
                map.put(sum, i);
            }
        }
        
        
        return res;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值