leetcode面试题57 - Ⅱ 和为s的连续正整数序列
题目描述

题目解析
由于所有解均为连续序列,因此可以用滑动窗口进行求解(即双指针法),维护两个指针 left 和 right ,当 sum < target 时 向右移动指针 right ,当sum > target时向右移动指针 left 知道sum < = target 。
class Solution {
public int[][] findContinuousSequence(int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
int left = 1;
int right = 1;
int sum = 0;
while(right < target && left <= right){
sum += right;
System.out.println("sssss" + sum + "right" + right + "left" + left);
while(sum > target){
sum -= left;
System.out.println("vvv" + sum);
left ++;
}
if(sum == target){
System.out.println(sum);
List<Integer> ans = new ArrayList<>();
for(int i = left; i <= right; i ++){
ans.add(i);
}
res.add(ans);
}
right ++;
}
int[][] result = new int[res.size()][];
int j = 0;
for(List<Integer> li : res){
int[] row = new int[li.size()];
int i = 0;
for(Integer lii : li){
row[i ++] = lii;
}
result[j ++] = row;
}
return result;
}
}
最后
以上就是碧蓝寒风最近收集整理的关于leetcode面试题57 - Ⅱ 和为s的连续正整数序列leetcode面试题57 - Ⅱ 和为s的连续正整数序列的全部内容,更多相关leetcode面试题57内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复