T57 - II. 和为 s 的连续正数序列
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 1:
输入:target = 9
输出:[[2,3,4],[4,5]]
示例 2:
输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]
限制:
1 <= target <= 10^5
解法 1
没做出来
解法 2
class Solution {
public int[][] findContinuousSequence(int target) {
int left = 1;
int right = 2;
List<int[]> res = new ArrayList<>();
while (left < right) {
int sum = (left + right) * (right - left + 1) / 2;
if (sum == target){
int[] arr = new int[right - left + 1];
for (int k = left; k <= right; k++) {
arr[k - left] = k;
}
res.add(arr);
left++;
}
else if (sum < target) {
right++;
}
else {
left++;
}
}
return res.toArray(new int[res.size()][]);
}
}
执行用时:4 ms, 在所有 Java 提交中击败了**56.28%**的用户
内存消耗:36.4 MB, 在所有 Java 提交中击败了**86.99%**的用户
时间复杂度:O(target)O(target)。滑动窗口最多移动 target/2 次
空间复杂度:O(1)O(1)。排除必要的存储结果数组之外,只需要保存左右指针
作者:画手大鹏
链接:https://leetcode-cn.com/leetbook/read/illustrate-lcof/5017gs/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。