138 子数组之和

原题网址:https://www.lintcode.com/problem/subarray-sum/description

描述

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

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

您在真实的面试中是否遇到过这个题?  

样例

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

标签
哈希表
子数组
 
 

思路:设置两根指针start与end,每次查找固定start,end向右移动,遍历数组,找到和为0的return出去。这种属于暴力破解。【时间596ms】

AC代码:

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> result;
      int n=nums.size();
      int sum;
      int start=0,end=0;
      for (;start<n;start++)
      {
          sum=nums[start];
          end=start;
          while(end<n-1&&sum!=0)//end<n-1防止end++后数组索引超出范围;
          {
              end++;
              sum+=nums[end];            
          }
          if (sum==0)
          {
              result.push_back(start);
              result.push_back(end);
              return result;
          }      
      }
    }
};

猜你喜欢

转载自www.cnblogs.com/Tang-tangt/p/9145066.html
138