方法1:
暴力法,从1~target/2遍历,判断被遍历数字之后的连续n个数字之和是否等于target,若等于,则在List中加入该数字序列组成的数组,若sum>target后,跳出本次循环,开始从下一个数字开始遍历。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24class Solution { public int[][] findContinuousSequence(int target) { List<int[]> ans = new ArrayList<>(); for(int i=1; i<=target/2; i++){ int temp = target; int k = i; while(temp>0){ temp = temp - k; k++; if(temp == 0){ int[] a = new int[k-i]; int b = i; for(int j=0; j<a.length; j++){ a[j] = b; b++; } ans.add(a); } } } return ans.toArray(new int[ans.size()][0]); } }
方法2:
为了避免重复的遍历,可以考虑使用双指针构建滑动窗口,起始窗口为1,2,当窗口内元素之和sum小于target时,右指针右移,sum=sum+right,sum大于target时,sum=sum-left,左指针右移,当sum==target时,将left和right之间的数放入数组并添加到list中,当右指针越过target/2时,结束运算。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29class Solution { public int[][] findContinuousSequence(int target) { int left = 1; int right = 2; List<int[]> res = new ArrayList<>(); int sum = left + right; while(right<=target/2+1){ if(sum < target){ right++; sum+=right; }else if(sum > target){ sum-=left; left++; }else{ int[] arr = new int[right-left+1]; int temp = left; for(int i=0; i<arr.length; i++){ arr[i] = temp; temp++; } res.add(arr); sum-=left; left++; } } return res.toArray(new int[0][]); } }
最后
以上就是眼睛大发带最近收集整理的关于leetcode 面试题57 - II. 和为s的连续正数序列【双指针】的全部内容,更多相关leetcode内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复