Subarray Sum to the given target value

本文探讨了检查子数组和是否等于目标值的问题,包括仅正数情况下的双指针法及包含负数时的动态规划法,并扩展到二维矩阵的情况。还讨论了一个变化题型,即元素之和能被特定值整除的子数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question: check if there is a subarray sum equals to the given target.

This question should ask for clarifications. Whether the inputs are all positive, or it has negative numbers.

1: If all the numbers are positive, we can just use two pointers way:

bool checkSubarraySum(vector<int>& array, int target) {
  int sum = 0;
  int i = 0, j = 0;
  while(i < array.size()) {
    sum += array[i];
    while(j < i && sum > target) {
      sum -= array[j];
      j++;
    }
    if(target == sum) return true;
    i++;
  }
  return false;
}

2: if there is any negative numbers, can't use this way anymore, instead, we need to dynamic programming idea.

bool checkSubarraySumWithNegative(vector<int>& array, int target) {
  for(int i = 1; i < array.size(); ++i) {
    array[i] += array[i-1];
  }
  set<int> sums;
  sums.insert(0);
  for(int i = 0; i < array.size(); ++i) {
    if(sums.count(target - array[i])) return true;
    sums.insert(array[i]);
  }
  return false;
}


It can be further extended into a 2d array.

// now, extend it to a 2d array. check if there is any rectangle that sums to a given target.
bool checkMatrix(vector< vector<int> >& matrix, int target) {
  for(int i = 1; i < matrix.size(); ++i) {
    matrix[i][0] += matrix[i-1][0];
  }
  for(int j = 1; j < matrix[0].size(); ++j) {
    matrix[0][j] += matrix[0][j-1];
  }
  for(int i = 1; i < matrix.size(); ++i) {
    for(int j = 1; j < matrix[0].size(); ++j) {
      matrix[i][j] += matrix[i-1][j] + matrix[i][j-1] - matrix[i-1][j-1];
    }
  }
  set<int> data; data.insert(0);
  for(int i = 0; i < matrix.size(); ++i) {
    for(int j = 0; j < matrix[0].size(); ++j) {
      if(data.count(target - matrix[i][j])) return true;
      data.insert(matrix[i][j]);
    }
  }
  return false;
}

One more variation:

Given an array of random integers, find subarray such that sum of elements in the element is divisible by K.

Suppse we have an array A[i] + A[i+1] + A[i+2].... =A[j] = target % k == 0

That is to say, (A[0] + A[1] + ... A[i-1]) % k = (A[0] + A[1] + A[2] .... A[j]) % k. We can use hash table to solve it as question 2.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值