Find subarray with given sum
来源:互联网 发布:四小票采集软件 编辑:程序博客网 时间:2024/05/31 18:59
Given an unsorted array of nonnegative integers, find a continous subarray which adds to a given number. 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 = 0Output: No subarray found.
There may be more than one subarrays with sum as the given sum. The following solutions print first such subarray.
思路:用fast和slow两个下标,计算fast和slow之间的subarray的和,如果和大于给定值,那么把slow向前移动一位,如果和小于给定值,那么把fast向前移动一位。
代码:
/* 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;}
0 0
- Find subarray with given sum
- Find subarray with given sum
- Find subarray with given sum
- Smallest subarray with sum greater than a given value
- Subarray Sum to the given target value
- Given a tree, find the node with the minimum sum of distances to other nodes
- Find the maximum subarray XOR in a given array
- No. 09 - Numbers with a Given Sum
- 在二叉搜索树里,寻找两个节点 Find a pair with given sum in a Balanced BST
- Find first subarray sum to zero
- CareerCup Given an array having positive integers, find a subarray which adds to a given number
- Find the subarray with least average
- [LinkedIn]Implement Find and replace (find given pattern and replace it with a given string)
- Subarray Sum
- Subarray Sum
- subarray sum
- Subarray Sum
- Subarray Sum
- C#中判断某软件是否已安装
- C# 关闭其他程序窗口、进程
- C# 强制关闭当前程序进程(完全Kill掉不留痕迹)
- Merge Sorted Array Leetcode Python
- C#将设置开机、关闭开机启动项
- Find subarray with given sum
- Linux(Ubuntu) 安装mysql,windows使用Navicat 连接
- 关于Mac的快捷操作
- Gray Code Leetcode Python
- 怎样在软件中使用apache license
- 90. Subsets II Leetcode Python
- [LeetCode] Determine if two rectangles overlap
- Ruby Notes
- 【BZOJ 1013】 [JSOI2008]球形空间产生器sphere