思路:
用sum[i]表示a[0]~a[i]的和,若sum[j]-sum[i]==k的话,则计数+1
注意:
若sum[i]==k的话,则计数+1
代码:
class Solution {
public:
int subarraySum(vector<int> &nums, int k) {
int subsum[nums.size() + 10];
int sum = 0;
int cnt=0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
subsum[i] = sum;
if(subsum[i]==k){
cnt++;
}
}
for (int i = 0; i < nums.size(); i++) {
for (int j = i+1; j < nums.size(); j++) {
if(j==i){
continue;
}
if (subsum[j] - subsum[i] == k) {
printf("%d %d\n",i,j);
cnt++;
}
}
}
return cnt;
}
};
网友评论