您的位置:首页 > 其它

[LintCode] Subarray Sum & Subarray Sum II

2015-06-01 12:21 387 查看

Subarray Sum

Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.

Example

Given
[-3, 1, 2, -3, 4]
, return
[0, 2]
or
[1, 3]
.

用hashmap来存从nums[0]到nums[i]的和以及当前下标i,遍历数组求前缀和acc[i],如果发现acc[i]的值已经在hashmap中的,那么说明已经找到一段子数组和为0了。

class Solution {
public:
/**
* @param nums: A list of integers
* @return: A list of integers includes the index of the first number
*          and the index of the last number
*/
vector<int> subarraySum(vector<int> nums){
// write your code here
map<int, int> has;
int sum = 0;
has[0] = -1;
vector<int> res;
for (int i = 0; i < nums.size(); ++i) {
sum += nums[i];
if (has.find(sum) != has.end()) {
res.push_back(has[sum] + 1);
res.push_back(i);
return res;
} else {
has[sum] = i;
}
}
return res;
}
};


Subarray Sum II

Given an integer array, find a subarray where the sum of numbers is between two given interval. Your code should return the number of possible answer.

Example

Given
[1,2,3,4]
and interval =
[1,3]
, return
4
. The possible answers are:

[0, 0]
[0, 1]
[1, 1]
[3, 3]


先求出前缀和,然后枚举求两个前缀和的差。如果差在start与end之间,就给res+1。注意前缀和数组前要插入一个0。

class Solution {
public:
/**
* @param A an integer array
* @param start an integer
* @param end an integer
* @return the number of possible answer
*/
int subarraySumII(vector<int>& A, int start, int end) {
// Write your code here
vector<int> acc(A);
acc.insert(acc.begin(), 0);
for (int i = 1; i < acc.size(); ++i) {
acc[i] += acc[i-1];
}
int tmp, res = 0;
for (int i = 0; i < acc.size() - 1; ++i) {
for (int j = i + 1; j < acc.size(); ++j) {
tmp = acc[j] - acc[i];
if (tmp>= start && tmp <= end) ++res;
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: