我的解题
1.超暴力,两个for循环
class Solution {
public:
vector<vector<int>> findContinuousSequence(int target) {
int mid=(target+1)/2;
vector<vector<int>> res;
for(int i=1;i<mid;i++){
vector<int> arr;
int sum=0;
for(int j=i;j<=mid;j++){
sum+=j;
if(sum==target){
arr.push_back(j);
res.push_back(arr);
break;
}
else if(sum<target)
arr.push_back(j);
else break;
}
}
return res;
}
};
2.因为是连续的数字,可以用双指针大法,求和可用简单的数学公式,首项加末项……
class Solution {
public:
vector<vector<int>> findContinuousSequence(int target) {
int i=1,j=2;
int mid=(target+1)/2;
vector<vector<int>> res;
int sum;
while(j<=mid&&i<j){
sum=(i+j)*(j-i+1)/2;
if(sum==target){
vector<int> arr;
for(int k=i;k<=j;k++){
arr.push_back(k);
}
res.push_back(arr);
i++;
}
else if(sum<target) j++;
else i++;
}
return res;
}
};
还是双指针好啊~