【问题描述】[简单]
【解答思路】
1. 滑动窗口
时间复杂度:O(N) 空间复杂度:O(1)
public int[][] findContinuousSequence(int target) {int i = 1; // 滑动窗口的左边界int j = 1; // 滑动窗口的右边界int sum = 0; // 滑动窗口中数字的和List<int[]> res = new ArrayList<>();while (i <= target / 2) {if (sum < target) {// 右边界向右移动sum += j;j++;} else if (sum > target) {// 左边界向右移动sum -= i;i++;} else {// 记录结果int[] arr = new int[j-i];for (int k = i; k < j; k++) {arr[k-i] = k;}res.add(arr);// 左边界向右移动sum -= i;i++;}}return res.toArray(new int[res.size()][]);
}
2. 数学
public int[][] findContinuousSequence(int target) {int n = 2;int limit = target >> 1;LinkedList<int []> result = new LinkedList<>();while (true) {int numerator = 2 * target - n * n + n;int denominator = 2 * n;// 如果不是整除,我们需要略过。if (numerator % denominator != 0) {n++;continue;}int n1 = numerator / denominator;// n 如果大于于中间的数,等差数列公式可以明显看到,得到的结果会大于target值; n1 不能为0,因为题目说明需要正整数;if (n >= limit || n1 <= 0) {break;}int[] a = new int[n];for (int k = n1, i = 0; i < n; i++, k++) {a[i] = k;}result.addFirst(a);n++;}return result.toArray(new int[result.size()][]);}
3.暴力
public int[][] findContinuousSequence(int target) {List<int[]> res = new ArrayList<>();if(target <= 2){return null;}for(int i = 1;i < target/2 + 1;i ++){int temp = target;int count = i;while(temp > 0){temp = temp - count;count++;}if(temp == 0){int[] arr = new int[count - i];int a = i;for(int j = 0;j < arr.length;j++){arr[j] = a;a++;}res.add(arr);}}return res.toArray(new int[0][]);}
【总结】
1.滑动窗口
2.数学是万能的 没有数学是万万不能的
3.细节
返回一个二重数组
List<int[]> res = new ArrayList<>();
int[] arr = new int[j-i];
return res.toArray(new int[res.size()][]);
res.add(arr);
转载链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/shi-yao-shi-hua-dong-chuang-kou-yi-ji-ru-he-yong-h/
转载链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/shi-qi-lai-chu-zhong-de-shu-xue-jian-dan-yi-dong-b/
参考链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/bao-li-fa-shuang-zhi-zhen-by-sugar-31/