90 和为s的连续正数序列

问题描述:输入一个正整数target,输出所有和为target的连续正整数序列(至少包含两个数),序列内的数字大小由小到大排列,不同序列按照首个字母从小到大排列。

for循环求解:对于for循环而言复杂度为n2较高。

java 复制代码
public List<List<Integer>>sumS(int target)
{
List<List<Integer>> res=new List<>();
for(int i=1;i<target/2;i++)
{
int sum=i;
List<Integer>list=new LinkedList<>();
list.add(i);
for(int j=i+1;j<target/2;j++)
{
if(sum+j>target)
break;
}else if(sum+j==target)
{
list.add(j);
res.add(list);
}else
{
sum+=j;
list.add(j)
}
}
​​​​​​​return res;
}

滑动窗口解决:定义一个sum(int类型)表示从左left到右right这个区间中的和,若sum小于target,则right右移,sum+nums[target],若大于taget,则left左移,若等于,则更新价收入数组中。

java 复制代码
public List<List<Integer>>sumS(int target)
{
int left=1;
int right=2;
int sum=left+right;
List<int[]>res=new LinkedList<>();
while(left<target/2)
{
if(sum<target)
{
right++;
sum+=right;
}else if(sum>target)
{
sum-=left;
left++;
}else
{
int []array=new int[right-left+1];
for(int i=0;i<array.length;i++)
{
array[i]=left+i;
}
res.add(array);
}
}
return res.toArray(new int[res.size()][]);
}
相关推荐
那个村的李富贵16 分钟前
CANN加速下的AIGC“即时翻译”:AI语音克隆与实时变声实战
人工智能·算法·aigc·cann
风流倜傥唐伯虎17 分钟前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
power 雀儿24 分钟前
Scaled Dot-Product Attention 分数计算 C++
算法
Yvonne爱编码27 分钟前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚28 分钟前
JAVA进阶之路——无奖问答挑战1
java·开发语言
熬夜有啥好32 分钟前
数据结构——哈希表
数据结构·散列表
你这个代码我看不懂36 分钟前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
fuquxiaoguang1 小时前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析
琹箐1 小时前
最大堆和最小堆 实现思路
java·开发语言·算法
__WanG1 小时前
JavaTuples 库分析
java