方法三双100%, 方法一 适合范围广
思路分析
代码如下
public int[][] findContinuousSequence(int target) {
ArrayList<int[]> resLists = new ArrayList<>();
int sum = 1;
for (int i = 1,j = 1; j <= (target >>1) + 1; ) {
if (sum < target) {
j++;
sum += j;
} else if (sum > target) {
sum -= i;
i++;
} else {
resLists.add(getArray(i,j));
j++;
sum = sum + j - i - (i + 1);
i = i+2;
}
}
return resLists.toArray(new int[0][]);
}
private int[] getArray(int i, int j) {
if (i == j) return new int[0]; // 题目要求至少含2个数
int[] arr = new int[(j - i + 1)];
for (int k = 0; k <= j - i; k++) arr[k] = k + i;
return arr;
}
(官方的题解,我就不写了,直接截图附上C++代码)
代码如下(C++)
class Solution {
public:
vector<vector<int>> findContinuousSequence(int target) {
vector<vector<int>> vec;
vector<int> res;
int sum = 0, limit = (target - 1) / 2; // (target - 1) / 2 等效于 target / 2 下取整
for (int x = 1; x <= limit; ++x) {
long long delta = 1 - 4 * (x - 1ll * x * x - 2 * target);
if (delta < 0) continue;
int delta_sqrt = (int)sqrt(delta + 0.5);
if (1ll * delta_sqrt * delta_sqrt == delta && (delta_sqrt - 1) % 2 == 0){
int y = (-1 + delta_sqrt) / 2; // 另一个解(-1-delta_sqrt)/2必然小于0,不用考虑
if (x < y) {
res.clear();
for (int i = x; i <= y; ++i) res.emplace_back(i);
vec.emplace_back(res);
}
}
}
return vec;
}
};
(参考了一位大佬的)
思路分析
实际上某个序列可以按其包含奇数/偶数个元素来讨论
因此枚举所有可能的序列长度len(从2开始,题目要求至少2个连续的数):
由于枚举按照序列长度递增顺序,因此输出时将结果逆序输出
对于枚举长度,len上界:
代码如下
public int[][] findContinuousSequence(int target) {
ArrayList<int[]> resLists = new ArrayList<>();
int len = 2;
while (len * (1 + len) < (target << 1)) {
if (len % 2 == 1) { // 长度为奇数
if (target % len == 0) { // 找到序列(中间数为 target/len)
int[] arr = new int[len];
for (int i = 0, val = target / len - len / 2; i < len; i++) // 存数组
arr[i] = val++;
resLists.add(arr);
}
} else { // 长度为偶数
int k = len / 2;
// 符合式子: 2k*(mid1+mid2) = target,k为正整数,mid1和mid2为连续的两个数,故和为大于1的奇数
if (target % k == 0 && target / k % 2 == 1) { // 找到序列(中间两个数的和为 target/k)
int[] arr = new int[len];
for (int i = 0, val = target / k / 2 - len / 2 + 1; i < len; i++)
arr[i] = val++;
resLists.add(arr);
}
}
len++;
}
Collections.reverse(resLists);
return resLists.toArray(new int[0][]);
}
原文:https://www.cnblogs.com/duduwy/p/13390543.html