链接:
https://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe?tpId=13&tqId=11194&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
描述:
示例:
示例缺陷:
示例中的9对应的值看起来两个数组是连续的,无重复的
但是实际有些特殊例子
例如:
所以遍历的时候要挨个遍历
代码:
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
vector<vector<int>> result;
int low = 1;
int high = 2;
while(low<high)
{
int total = (low + high)*(high-low+1)/2;
if(total == sum){
vector<int> v;
for(int i = low;i<=high;i++)
{
v.push_back(i);
}
result.push_back(v);
low++;
}
else if(total<sum) high++;
else low++;
}
return result;
}
};
另辟蹊径:
我们是从1开始判定是否具有一个连续的数字和是sum的
我们知道:Sn=d/2*n²+(a1-d/2)n
已知:Sn,d = 1,a1 求n
我们知道:Sn=[n(a1+an)]/2
已知:Sn,an = a1+nd,a1 求an
数学思路----》不会先空着