【发布时间】:2017-01-12 05:49:16
【问题描述】:
问题陈述是:
给定一个未排序的非负整数数组,找到一个连续子数组,它与给定的数相加。
Examples:
Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Ouptut: Sum found between indexes 2 and 4
Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7
Ouptut: Sum found between indexes 1 and 4
Input: arr[] = {1, 4}, sum = 0
Output: No subarray found
根据this post 对解决方案的解释,以下解决方案不适用于负数:
/* An efficient program to print subarray with sum as given sum */
#include<stdio.h>
/* Returns true if the there is a subarray of arr[] with sum equal to 'sum'
otherwise returns false. Also, prints the result */
int subArraySum(int arr[], int n, int sum)
{
/* Initialize curr_sum as value of first element
and starting point as 0 */
int curr_sum = arr[0], start = 0, i;
/* Add elements one by one to curr_sum and if the curr_sum exceeds the
sum, then remove starting element */
for (i = 1; i <= n; i++)
{
// If curr_sum exceeds the sum, then remove the starting elements
while (curr_sum > sum && start < i-1)
{
curr_sum = curr_sum - arr[start];
start++;
}
// If curr_sum becomes equal to sum, then return true
if (curr_sum == sum)
{
printf ("Sum found between indexes %d and %d", start, i-1);
return 1;
}
// Add this element to curr_sum
if (i < n)
curr_sum = curr_sum + arr[i];
}
// If we reach here, then no subarray
printf("No subarray found");
return 0;
}
我尝试考虑几种不同的输入场景,但我想不出输入数组包含负数并且不会产生正确输出的情况。这是一个有效的负数输入数组:
int arr[] = { 15, 14, -2, 3, -5, 14};
当帖子说解决方案不适用于负数时,指的是哪些输入案例?
【问题讨论】:
-
调试器。使用调试器。当您执行程序时,调试器将帮助您逐句显示变量中的值。