题解 | #和为S的连续正数序列#
和为S的连续正数序列
http://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe
大神的滑动窗口解决方案:
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
//两个下标,分别记录窗口两端
int plow=1,phigh=2;
while(plow<phigh){
//cur表示窗口内数据的和
int cur = (plow+phigh)*(phigh-plow+1)/2;
//相等时直接加入列表,然后左侧窗口右移,继续寻找下一部分。
if(cur == sum){
ArrayList<Integer> list = new ArrayList<>();
for(int i=plow;i<=phigh;i++){
list.add(i);
}
ans.add(list);
plow++;
//小于sum则窗口右侧右移
}else if(cur<sum){
phigh++;
//大了,那就将左侧右移,寻找下一个
}else{
plow++;
}
}
return ans;
}
}
OPPO公司福利 1165人发布