题目:已知一个整数数组和一个整数 n,找到该数组中和为 n 的连续的子数组的个数。
#include <iostream> using namespace std; int subarraySum(int* array, int arraySize, int numberSum) { int n = 0; for (int i = 0; i < arraySize; ++i) { int sum = 0; for (int j = i; j < arraySize; ++j) { sum = sum + array[j]; if (sum == numberSum) { ++n; } } } return n; } int main() { int array[] = { 1, 3, 5, 2, 4, 6, 1,1 }; int number, numberSum; int arraySize; arraySize = sizeof(array) / sizeof(int); numberSum = 8; number = subarraySum(array, arraySize, numberSum); cout << "子数组的个数:" << number << endl; return 0; }
结果: