和为s的连续正数序列
// 开始自己写的笨比暴力方法...
class Solution {
public int[][] findContinuousSequence(int target) {
List<int[]> list = new ArrayList<>();
int sum = 0;
int max = target / 2 + 1;
for (int i = 1; i <= max; i++) {
sum = 0;
for (int j = i; j <= max; j++) {
sum += j;
if (sum > target) { // 说明当前i开头的没有
break;
}
if (sum == target) { // 找到了一组,从i到j
int[] a = new int[j - i + 1];
int index = 0;
while (index <= j - i) {
a[index] = i + index;
index++;
}
list.add(a);
break;
}
}
}
return list.toArray(new int[0][]); // list转数组的方式
}
}
滑动窗口法:
// 参考别人的双指针 滑动窗口法,耗时瞬间下降2ms...
class Solution {
public int[][] findContinuousSequence(int target) {
List<int[]> list = new ArrayList<>();
for (int l = 1, r = 1, sum = 0; r <= target / 2 + 1; r++) { // 两个索引,减少中间重复加的步骤
sum += r;
while (sum > target) { // 如果sum超过target的值了,把左边游标往右移
sum -= l;
l++;
}
if (sum == target) { // 找到了,区间是l到r
int[] arr = new int[r - l + 1];
for (int i = l; i <= r; i++) {
arr[i - l] = i;
}
list.add(arr);
}
}
return list.toArray(new int[0][]);
}
}
list转数组的方式: List接口中的: Object[] toArray(); <T> T[] toArray(T[] a)
List<int[]> list = new ArrayList<>();
int[][] arr = list.toArray(new int[0][]);