[LintCode] Subarray Sum & Subarray Sum II

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 = ;
has[] = -;
vector<int> res;
for (int i = ; i < nums.size(); ++i) {
sum += nums[i];
if (has.find(sum) != has.end()) {
res.push_back(has[sum] + );
res.push_back(i);
return res;
} else {
has[sum] = i;
}
}
return res;
}
};

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(), );
for (int i = ; i < acc.size(); ++i) {
acc[i] += acc[i-];
}
int tmp, res = ;
for (int i = ; i < acc.size() - ; ++i) {
for (int j = i + 1; j < acc.size(); ++j) {
tmp = acc[j] - acc[i];
if (tmp>= start && tmp <= end) ++res;
}
}
return res;
}
};
上一篇:cesium.js 设置缩放最大最小限制


下一篇:Continuous Subarray Sum II