剑指 Offer 57 - 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
解答:
class Solution {
//时间复杂度:O(N)。空间复杂度:O(1)
public int[][] findContinuousSequence(int target) {
int i = 1, j = 2, sum = 3;
List<int[]> ans = new ArrayList<>();
while(i < j){
if(sum == target){
int[] ret = new int[j - i + 1];
for(int m = i; m <= j; m++){
ret[m - i] = m;
}
ans.add(ret);
}
if(sum >= target){
sum -= i;
i++;
}else{
j++;
sum += j;
}
}
return ans.toArray(new int[0][]);
}
}
class Solution {
public int[][] findContinuousSequence(int target) {
int i = 1;
double j = 2.0;
List<int[]> res = new ArrayList<>();
while(i < j) {
j = (-1 + Math.sqrt(1 + 4 * (2 * target + (long) i * i - i))) / 2;
if(i < j && j == (int)j) {
int[] ans = new int[(int)j - i + 1];
for(int k = i; k <= (int)j; k++)
ans[k - i] = k;
res.add(ans);
}
i++;
}
return res.toArray(new int[0][]);
}
}
参考自:
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/jian-zhi-offer-57-ii-he-wei-s-de-lian-xu-t85z/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。