AcWing 76. 和为S的连续正数序列
原题链接
中等
作者:
LeonLiu
,
2019-12-19 19:36:28
,
所有人可见
,
阅读 614
class Solution {
public List<List<Integer>> findContinuousSequence(int sum) {
int[] prefixSum = new int[sum / 2 + 2];
for (int i = 1; i <= sum / 2 + 1; i++) {
prefixSum[i] = prefixSum[i - 1] + i;
}
List<List<Integer>> ans = new LinkedList<>();
for (int i = 2, j = 1; i <= sum / 2 + 1 && j < i; i++) {
while (prefixSum[i] - prefixSum[j - 1] > sum) {
j++;
}
if (prefixSum[i] - prefixSum[j - 1] == sum) {
List<Integer> m = new ArrayList<>(i - j + 1);
for (int x = j; x <= i; x++) {
m.add(x);
}
ans.add(m);
}
}
return ans;
}
}