和为S的连续正数序列

和为S的连续正数序列

http://www.nowcoder.com/questionTerminal/c451a3fd84b64cb19485dad758a55ebe

直接用了暴力法循环没想到过了。
其实用两支针法更好

 public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
        ArrayList<ArrayList<Integer> > res = new ArrayList<>();
        int temp = 0;//用来存储当前序列的和
        for(int i=1;i<sum;i++){
            temp+=i;
            for(int j=i+1;j<sum;j++){
                temp+=j;
                if(temp==sum){
                    ArrayList<Integer> r = new ArrayList<>();
                    for(int k=i;k<=j;k++){
                        r.add(k);
                    }
                    res.add(r);
                    break;
                }
            }
            temp=0;
        }
        return res;
    }
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务