子数组之和

1、问题描述

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

样例

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

2、实现思路

    从第一个开始,固定其值,若其为0,起始和终止位置都为当前位置下标,不为零,则从下一个开始,依次加和,至零则找到终止位置坐标。

3、代码

class Solution {
public:
    /**
     * @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
     */
    vector<int> subarraySum(vector<int> nums){
        // write your code here
        vector<int> b;
        int a=nums.size();
        int i,j,c;
        for(i=0;i<a;i++)
        {  c=nums[i];
           if(c==0){ b.push_back(i);
                           b.push_back(i);
                           break; }
           for(j=i+1;j<a;j++)
           { c=c+nums[j];
             if(c==0) { b.push_back(i);
                              b.push_back(j);
                              break;}
           }
            if(c==0)break;
        }
        return b;
    }
};

4、感想

    创建一个空向量,将符合的起始和终止位置坐标加入,注意同一个起始位置找到一个终止位置即可,一个数组找到一对起始和终止坐标即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值