(剑指offer)和为S的连续正数序列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ccnuacmhdu/article/details/84871262

时间限制:1秒 空间限制:32768K 热度指数:166504

题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序

import java.util.ArrayList;
public class Solution {
    public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
       //看到此题,立马想到的是滑动窗口
        ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
        
        int l = 1;
        int r = 2;
        while(l < r){
            int cur = (l+r)*(r-l+1)/2;
            if(cur > sum){
                l++;
            }else if(cur < sum){
                r++;
            }else{
                ArrayList<Integer> list = new ArrayList<Integer>();
                for(int i = l; i <= r; i++){
                    list.add(i);
                }
                listAll.add(list);
                l++;
            }
        }
        return listAll;
    }
}

猜你喜欢

转载自blog.csdn.net/ccnuacmhdu/article/details/84871262