Skip to content

更新了[lcof-57.和为s的连续正整数序列]的cpp解法 #347

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions lcof/面试题57 - II. 和为s的连续正数序列/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,55 @@ var findContinuousSequence = function (target) {
};
```

### **C++**

```cpp
class Solution {
public:
vector<int> build(int small, int big) {
vector<int> ret;
for (int i = small; i <= big; i++) {
ret.push_back(i);
}

return ret;
}

vector<vector<int>> findContinuousSequence(int target) {
vector<vector<int>> ret;
int small = 1;
int big = 2;
int mid = (target + 1) / 2;
int curSum = small + big;

if (target < 3) {
ret;
}

while(small < mid) {
if (curSum == target) {
ret.push_back(build(small, big));
}

while (curSum > target && small < mid) {
// 一直减去,减去到比target小停止
curSum -= small;
small++;

if (curSum == target && small < mid) {
ret.push_back(build(small, big));
}
}

big++;
curSum += big;
}

return ret;
}
};
```

### **...**

```
Expand Down
44 changes: 44 additions & 0 deletions lcof/面试题57 - II. 和为s的连续正数序列/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class Solution {
public:
vector<int> build(int small, int big) {
vector<int> ret;
for (int i = small; i <= big; i++) {
ret.push_back(i);
}

return ret;
}

vector<vector<int>> findContinuousSequence(int target) {
vector<vector<int>> ret;
int small = 1;
int big = 2;
int mid = (target + 1) / 2;
int curSum = small + big;

if (target < 3) {
ret;
}

while(small < mid) {
if (curSum == target) {
ret.push_back(build(small, big));
}

while (curSum > target && small < mid) {
// 一直减去,减去到比target小停止
curSum -= small;
small++;

if (curSum == target && small < mid) {
ret.push_back(build(small, big));
}
}

big++;
curSum += big;
}

return ret;
}
};