死磕算法系列文章
“Leetcode : https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/
“GitHub : https://github.com/nateshao/leetcode/blob/main/algo-notes/src/main/java/com/nateshao/sword_offer/topic_44_findContinuousSequence/Solution.java
“题目描述 :输入一个正整数
target
,输出所有和为target
的连续正整数序列(至少含有两个数)。 序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。难度:简单
示例 1:
输入:target = 9
输出:[[2,3,4],[4,5]]
示例 2:
输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]
设连续正整数序列的左边界 ii 和右边界 jj ,则可构建滑动窗口从左向右滑动。循环中,每轮判断滑动窗口内
元愫和与目标值 target 的大小关系,若相等则记录结果,若大于 target 则移动左边界 i (以减小窗口内的元 素和),若于 target 则移动右边界 j (以增大窗口内的元素和) 。
算法流程:
复杂度分析;
package com.nateshao.sword_offer.topic_44_findContinuousSequence;
import java.util.ArrayList;
import java.util.List;
/**
* @date Created by 邵桐杰 on 2022/1/25 15:37
* @微信公众号 千羽的编程时光
* @个人网站 www.nateshao.cn
* @博客 https://nateshao.gitee.io
* @GitHub https://github.com/nateshao
* @Gitee https://gitee.com/nateshao
* Description:
*/
public class Solution {
public static void main(String[] args) {
int[][] findContinuousSequence = findContinuousSequence(9);
for (int[] ints : findContinuousSequence) {
for (int anInt : ints) {
System.out.println("anInt = " + anInt);
}
}
}
/**
* 解法:滑动窗口(双指针)
* @param target
* @return
*/
public static int[][] findContinuousSequence(int target) {
int i = 1, j = 2, s = 3;
List<int[]> res = new ArrayList<>();
while (i < j) {
if (s == target) {
int[] ans = new int[j - i + 1];
for (int k = i; k <= j; k++)
ans[k - i] = k;
res.add(ans);
}
if (s >= target) {
s -= i;
i++;
} else {
j++;
s += j;
}
}
return res.toArray(new int[0][]);
}
}
参考链接: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/