我试图小心输入数组的元素" arr"用于确定子阵列的最大总和,以下称为" maxSum" (在其他地方确定,并确认是正确的)。函数showSubArray()接受数组arr,数组n的长度和maxSum作为参数。输入数组是正负的整数。下面是一组带有结果的测试数组。失败意味着arr [0]被打印到屏幕上,空格将它们无限分开。我无法在输入中看到任何可识别的模式。任何帮助都非常感谢,我不赞成unordered_map方法。从确定maxSum的函数中获取索引不是可接受的解决方案。
#include <unordered_map>
#include <iostream>
using std::cout;
int main() {
//int arr[] = { 1, 4, -9, 8, 1, 3, 3, 1, -1, -4, -6, 2, 8, 19, -10, -11 };
// runs ok, inputs: n=16, maxSum = 34
//int arr[] = { 2, 9, 8, 6, 5, -11, 9, -11, 7, 5, -1, -8, -3, 7, -2 };
// ***fails, inputs: n=15, maxSum = 30
//int arr[] = { 10, -11, -1, -9, 33, -45, 23, 24, -1, -7, -8, 19 };
// runs ok, n=12, maxSum = 50
//int arr[] = { 31, -41, 59, 26, -53, 58, 97, -93, -23, 84 };
// runs ok n=10 maxSum = 187
//int arr[] = { 3, 2, 1, 1, -8, 1, 1, 2, 3 };
// ***fails, inputs: n=9 maxSum = 7
int arr[] = { 12, 99, 99, -99, -27, 0, 0, 0, -3, 10 };
// ***fails, n=10 maxSum = 210
//int arr[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
// runs ok, inputs: n=9 maxSum = 6
showSubArray(arr, n, maxSum);
return 0;
}
void showSubArray(int arr[], int n, int maxSum) {
std::unordered_map<int, int> aMap;
int accumulator = 0;
for (int i = 0; i < n; i++) {
accumulator += arr[i];
if (accumulator == maxSum) {
for(int j = 0; j <= i; j++) {
// ACB found error here ^ (I had it as "i")
cout << arr[j];
cout << " ";
}
cout << '\n';
return;
}
if (aMap.find(accumulator - maxSum) != aMap.end()) {
for (int j = aMap[accumulator - maxSum] + 1; j <= i; j++) {
cout << arr[j];
cout << " ";
}
cout << '\n';
return;
}
aMap[accumulator] = i;
}
cout << "Subarray not found!\n";
}
答案 0 :(得分:1)
<jr:column width="100" uuid="accf01ee-c512-4854-ae58-97dee667c054">
<jr:tableHeader style="Table_TH" height="30">
<staticText>
<reportElement x="0" y="0" width="100" height="30" uuid="41f6fe02-194f-483e-ab7b-97a6061e2c27"/>
<text><![CDATA[My header]]></text>
</staticText>
</jr:tableHeader>
....
</jr:column>
你正在增加我在这里,但你想增加j因为0总是会更小i对于i&gt; 0直到溢出